4

Need help, how I can upload file in ASP.NET core rc2 web api. When i use asp.net 4.5 it working with this code:

   @{
ViewBag.Title = "Home Page";
    }

 <div>
<input type="file" name="upload" id="uploadFile"  /><br />
<button id="submit">Загрузить</button>
</div>

 @section scripts{
<script type="text/javascript">

$('#submit').on('click', function (e) {
    e.preventDefault();
    var files = document.getElementById('uploadFile').files;
    if (files.length > 0) {
        if (window.FormData !== undefined) {
            var data = new FormData();
            for (var x = 0; x < files.length; x++) {
                data.append("file" + x, files[x]);
            }

            $.ajax({
type: "POST",
url: 'api/values/post',
contentType: false,
processData: false,
data: data,
success: function (result) {
    alert(result);
},
error: function (xhr, status, p3) {
    alert(status);
}
});
        } else {
            alert("Браузер не поддерживает загрузку файлов HTML5!");
        }
    }
});

}

public class ValuesController : ApiController
{
public async Task<IHttpActionResult> Post()  
{
    if (!Request.Content.IsMimeMultipartContent())
    {
        return BadRequest();
    }
    var provider = new MultipartMemoryStreamProvider();
    // путь к папке на сервере
    string root = System.Web.HttpContext.Current.Server.MapPath("~/Files/");
    await Request.Content.ReadAsMultipartAsync(provider);

    foreach (var file in provider.Contents)
    {
        var filename = file.Headers.ContentDisposition.FileName.Trim('\"');
        byte[] fileArray = await file.ReadAsByteArrayAsync();

        using (System.IO.FileStream fs = new System.IO.FileStream(root + filename, System.IO.FileMode.Create))
        {
            await fs.WriteAsync(fileArray, 0, fileArray.Length);
        }
    }
    return Ok("файлы загружены");
}
}

Now, in asp.net core rc2 it doesnt work, If use IFromFile in mvc without ajax it works, but we use js+ajax+webapi

1
  • It is for Web Api 2 but not Asp.Net Core. Commented Feb 21, 2017 at 6:51

3 Answers 3

12

I had the same problem and I solved it this way:

[HttpPost]
public async Task<IActionResult> PostFile()
{   
   //Read all files from angularjs FormData post request
 var files = Request.Form.Files;
  .....
}

For full solution you can also take look on my question

Sign up to request clarification or add additional context in comments.

1 Comment

Actual in ASP.NET Core 1.1.1!
6

In my asp.net core programm I changed the controller method to

[HttpPost]
public async Task<IActionResult> Upload(ICollection<IFormFile> file)
{
     ...       
}

I have added the [HttpPost] annotation and used the new IFormFile interface.

Comments

1

This works for me. Use "Request.Form.Files". Works with ASP.NET Core.

    [HttpPost]
    [Route("UploadFiles")]
    public async Task<IActionResult> Post()
    {
        var files = Request.Form.Files;
        long size = files.Sum(f => f.Length);

        // full path to file in temp location
        var filePath = Path.GetTempFileName();

        foreach (var formFile in files)
        {
            if (formFile.Length > 0)
            {
                using (var stream = new FileStream(filePath, FileMode.Create))
                {
                    await formFile.CopyToAsync(stream);
                }
            }
        }

        // process uploaded files
        // Don't rely on or trust the FileName property without validation.

        return Ok(new { count = files.Count, size, filePath });
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.