4

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?

Mario
  • 4,784
  • 3
  • 34
  • 50
Karthik Ravichandran
  • 1,205
  • 2
  • 15
  • 25

1 Answers1

1

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)

davidluckystar
  • 928
  • 5
  • 15
  • Hi @david.lucky, I have tried by setting the boundary value also. but not works. Is boundary value has been updated dynamically by browser? – Karthik Ravichandran Mar 27 '18 at 06:15
  • How did you set the boundary? Im not sure if you can do it without modifying the content (which I guess you didnt). And also - what's wrong with not setting the content-type and rely on default behaviour? – davidluckystar Mar 27 '18 at 06:19
  • What did you mean, "Im not sure if you can do it without modifying the content". – Karthik Ravichandran Mar 27 '18 at 06:29
  • I mean that this boundary part `------WebKitFormBoundaryrKBH6bAMJIdepLCI ` is used in content to identify file start and file end; so your boundary in content-type should be set according to the content (they should match) – davidluckystar Mar 27 '18 at 07:07