Search code examples
asp.netangularjsfile-uploadasp.net-coreng-file-upload

How can I upload files in ASP.NET5 using ajax?


I've read many posts about uploading files using a traditional html form and using IFormFile on the server side (ASP.NET5 RC). However, I would like to upload a file using ajax (specifically ng-file-upload) and IFormFile doesn't seem to work when using ajax. The request payload looks like:

------WebKitFormBoundaryqGdWTqE8FFBpVPbA
Content-Disposition: form-data; name="file[0]"; filename="mydoc.pdf"
Content-Type: application/pdf


------WebKitFormBoundaryqGdWTqE8FFBpVPbA--

I believe the files are being passed up in the Request.Body, but I'm not sure how to extract them from there.


Solution

  • I just did this using the Kendo UI upload control, I also found that an IFormFile parameter was not populated. I got it working using Request.Form.Files

     foreach (var file in Request.Form.Files)
            {
                    var fileBytes = new byte[file.Length];
    
                    await file.OpenReadStream().ReadAsync(fileBytes, 0, (int)file.Length);
    
                    SaveDoc(fileBytes, Path.GetFileNameWithoutExtension(fileName), docTypeId, enrollmentId, Path.GetExtension(fileName).Replace(".", ""), comments: comments);
            }