'Request.Content.IsMimeMultipartContent() fails
I'm trying to upload a file using the Html2 input type="file" and an angular2 http.post request. When the request reaches the web api, it fails in the
Request.Content.IsMimeMultipartContent()
It doesn't fail when submitting the request using Postman (when I don't include Content-Type in the header because postman takes care of it).
See my code: Html:
<input type="file" (change)="fileChange($event)" placeholder="Upload file" accept=".pdf,.doc,.docx,.dwg,.jpeg,.jpg">
Service function:
uploadFile(event) {
let fileUploadUrl = this.webApiFileUploadURL;
let fileList: FileList = event.target.files;
if(fileList.length > 0) {
let file: File = fileList[0];
let formData:FormData = new FormData();
formData.append('uploadFile', file, file.name);
let headers = new Headers();
headers.append('Content-Type', 'multipart/form-data');
headers.append('Accept', 'application/json');
let options = new RequestOptions({ headers: headers });
this._http.post(`${this.webApiFileUploadURL}`, formData, options)
.map(res => res.json())
.catch(error => Observable.throw(error))
.subscribe(
data => console.log('success'),
error => console.log(error)
)
}
And the WebApi post request (fails at if (!Request.Content.IsMimeMultipartContent()) ):
public async Task<HttpResponseMessage> PostFormData()
{
// Check if the request contains multipart/form-data.
if (!Request.Content.IsMimeMultipartContent()) // Fails here
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
string root = HttpContext.Current.Server.MapPath("~/App_Data");
var provider = new MultipartFormDataStreamProvider(root);
try
{
// Read the form data.
await Request.Content.ReadAsMultipartAsync(provider);
// This illustrates how to get the file names.
foreach (MultipartFileData file in provider.FileData)
{
Trace.WriteLine(file.Headers.ContentDisposition.FileName);
Trace.WriteLine("Server file path: " + file.LocalFileName);
}
return Request.CreateResponse(HttpStatusCode.OK);
}
catch (System.Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
}
Solution 1:[1]
After a thorough research - I've succeeded:
No need to set the content-type header property when posting.
I've removed it from my angular2 http.post request and the
Request.Content.IsMimeMultipartContent() in the web-api post method passed (same as in postman)
Solution 2:[2]
If anyone else runs into this "The request entity's media type 'multipart/form-data' is not supported for this resource."
You may need to add this in you webapiconfig
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("multipart/form-data"));
Solution 3:[3]
After so much reading, my guess is that you need to save your uploaded files asychronously (i just refer to it as JQUERY_D_UPLOAD). I've created this small ASP.NET C# async task below to get you started. NOTE: should return a string eg return "This was created by [email protected]"; For more, find me in my turing.com/github/facebook/gmail accounts: (onyangofred)
public async Task<string> SaveFile()
{
for (int i = 0; i < Request.Files.Count; i++)
{
HttpPostedFileBase file = Request.Files[i];
using (var stream = new FileStream(Path.Combine("~/uploads", Guid.NewGuid().ToString() + Path.GetExtension(file.FileName)), FileMode.Create, FileAccess.Write, FileShare.Write, 4096, useAsync: true))
{
await file.InputStream.CopyToAsync(stream);
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Guy E |
Solution 2 | Melvin Gaye |
Solution 3 |