简体   繁体   中英

Not able to change Content-Type in xmlHttpRequest

I have tried to set the Content-Type before send the 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 content-type, i am not able to get the datas in server end.

If i remove the code for setting the content-type, its working properly

My server side code is below

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

Is any suggesions?

The thing is that Content-type: multipart/form-data should be followed by boundary: (your file boundary) but because you set it explicitly it doesn't exist

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

If you're not setting Content-type then XHR is smart enough to understand that you're sending files, so I suggest you just not to set it or set the boundary

(look here fetch - Missing boundary in multipart/form-data POST )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM