Roman Kolesnikov
Roman Kolesnikov

Reputation: 12147

ASP.NET 5: Upload file through WebApi

I'm sending file to WebApi using Jquery.ajax I have an ASP.NET method that receives file

[HttpPost]
[ActionName("import")]
public int Import([FromBody]IFormFile upload)

Inside Import method a can save Request.Body and it looks correct:

------WebKitFormBoundaryZLHvtGDqa5zp0JHB Content-Disposition: form-data; name="upload"; filename="test.b3d" Content-Type: application/octet-stream

Hello world content!

but upload variable is always null! What should I fix to have file contents inside "upload" variable?

PS: I send file to server using this code:

    // Create a formdata object and add the files
    var data = new FormData();
    data.append("upload", file.files[0]);

    jQuery.ajax({
        type: "POST",
        url: "/api/designer/import",
        contentType: "application/json",
        dataType: 'json',
        processData: false,
        data: data
    })

The request headers in Chrome:

Accept:application/json, text/javascript, */*; q=0.01
Accept-Encoding:gzip, deflate
Accept-Language:en-US,en;q=0.8,ru;q=0.6
Connection:keep-alive
Content-Length:28855
Content-Type:application/x-www-form-urlencoded
Host:localhost:64867
Origin:http://localhost:64867
Referer:http://localhost:64867/
User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36
X-Requested-With:XMLHttpRequest

Upvotes: 1

Views: 617

Answers (1)

Kiran
Kiran

Reputation: 57949

Remove the FromBody attribute decorated on the parameter to enable binding data of application/x-www-form-urlencoded format.

This is a change from how existing Web API works. You can use FromBody in cases other than application/x-www-form-urlencoded, like application/json, application/xml etc.

Upvotes: 1

Related Questions