Unable to change Content-Type in xmlHttpRequest

I tried setting Content-Type before sending xhr data as below

function uploadFile() {
  var files =  document.getElementById("file1") .files[0] ;
  var formdata = new FormData();
  formdata.append("Key", files);
  ajax = new XMLHttpRequest();
  ajax.upload.addEventListener("progress", progressHandler, false);
  ajax.addEventListener("load", completeHandler, false);
  ajax.addEventListener("error", errorHandler, false);
  ajax.addEventListener("abort", abortHandler, false);  
  ajax.open("POST", "./Save");  
  ajax.setRequestHeader('Content-Type','multipart/form-data;'); 
  ajax.send(formdata);
}

By changing the type of content, I cannot get the data at the end of the server.

If I remove the code to set the content type, it works correctly

My server code is below

HttpContext.Current.Request.Files["Key"]

Are there any suggestions?

+4
source share
1 answer

The fact is that it Content-type: multipart/form-datashould be followed boundary: (your file boundary), but since you explicitly install it, it does not exist

Content-type: multipart/form-data; boundary=----WebKitFormBoundaryrKBH6bAMJIdepLCI

If you don’t install Content-type, then XHR is smart enough to understand that you are sending files, so I suggest you just not install it or installboundary

( fetch - POST multipart/form-data)

+1

Source: https://habr.com/ru/post/1695389/


All Articles