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);
}
}
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)
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"));
Original Credit
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With