Max Melnikov Max Melnikov - 1 year ago 319
C# Question Core rc2 web api file upload

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

ViewBag.Title = "Home Page";

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

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

$('#submit').on('click', function (e) {
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]);

type: "POST",
url: 'api/values/post',
contentType: false,
processData: false,
data: data,
success: function (result) {
error: function (xhr, status, p3) {
} 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 core rc2 it doesnt work, If use IFromFile in mvc without ajax it working, but we use js+ajax+webapi

Answer Source

In my core programm I changed the controller method to

public async Task<IActionResult> Upload(ICollection<IFormFile> file)

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download