Search code examples
asp.net-web-apimultipartform-dataform-datahttp-options-method

issue posting multipart/form-data via html5 FormData to c# Api


My issue is that my c# api controller is kicking back theFormData Post request when I check for multi-part data here: IsMimeMultipartContent(), which then throws the message back to the UI:

415 (Unsupported Media Type)

 [HttpPost]
 [Route("MediaUpload")]
public async Task<HttpResponseMessage> MediaUpload([FromUri]string sessionId, [FromUri]string patientId)
    {

        if (!Request.Content.IsMimeMultipartContent())
        {    // *** ALWAYS THROWS ERROR ***
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
        }
        
        //access form data  
        var provider = await Request.Content.ReadAsMultipartAsync(new InMemoryMultipartFormDataStreamProvider());            
        NameValueCollection formData = provider.FormData;
            
        //... additional code omitted
        
        var response = Request.CreateResponse(HttpStatusCode.OK);
        response.Headers.Add("UploadPath", fullPath);
        response.Headers.Add("Access-Control-Allow-Origin", "*");
        return response;
    }

My front end payload looks like this:

  • REQUEST HEADERS

POST /api/import/MediaUpload?sessionID=c83f9589-742e-40e3-8cf5-7ffff141c3d7&patientId=5981 HTTP/1.1
Host: localhost:56703
Connection: keep-alive
Content-Length: 6545
Accept: application/json, text/plain, */*
Origin: http://localhost:4200
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36
Content-Type: multipart/form-data
Referer: http://localhost:4200/
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9

  • REQUEST PAYLOAD

------WebKitFormBoundaryVrKSHPqdT9c6JkKv
Content-Disposition: form-data; name="enctype"

multipart/form-data
------WebKitFormBoundaryVrKSHPqdT9c6JkKv
Content-Disposition: form-data; name="MediaInfo"

[{"PatientID":5981,"PatientLastName":"Hobo","PatientFirstName":"John","DeviceID":"123","InstanceID":89,"PatientDOB":"1/3/1970","FileName":"image2.jpg","FileSize":5880,"ExamDate":"5/30/2018","PatientID":66665981,"SessionID":"sessionID=9999141c3d7"}]
------WebKitFormBoundaryVrKSHPqdT9c6JkKv
Content-Disposition: form-data; name="files[]"; filename="image2.jpg"
Content-Type: image/jpeg

ÿØÿàJFIFÿÛC															

------WebKitFormBoundaryVrKSHPqdT9c6JkKv--

My front end is sending in FormData, generated in the following TypeScript method, then calling the importService further below:

save() {
	let params = { patientID: ''};
	let exDate = new Date(this.defaultDate).toLocaleDateString();
	
	// Populate MediaInfo object
	let minfo = this.SetMediaArray();
	params.pID = minfo[0].PID;
	
	const formData = new FormData();
	formData.set("enctype", "multipart/form-data" );	// doesn't make a difference..
	formData.append("MedInfo",  JSON.stringify(minfo));

	for(var i=0; i<this.importImages.length; i++){
		// append images to the files[] array, then send formData object to impService
		formData.append("files[]", this.dataURItoBlob(this.importImages[i].TnUrl), this.importImages[i].name);
	}

	let endpoint = this.selectedObj.Url;			
	
	this.importService.saveImportObjects(formData, params, endpoint).subscribe(
		data=> {			
			console.log(data);			
		},
		err => {         
			console.log(err);			
		}
	); 
}

So basically I would like to know exactly what http option I'm missing for this to work.

thank you.


Solution

  • I removed the multipart/boundary header attribute, and let the browser take care of it for you. The upload worked.