how to use xhr.overrideMimeType in Chrome / IE Edge?

我的梦境 提交于 2019-12-24 07:14:14

问题


I have an issue with sending a file (part of a request in form data format).

The issue seems coming from the fact that only in Chrome for Linux the file (which is CVS file, with .csv extension and basically just text) is sent with mimetype (Content-type in request body) Content-Type: application/octet-stream

So, I am trying to override the mimetype to match the same sent by Chrome on Linux which is text/csv.

However the mimetype is apparently not overriden and still send as octet-stream.

My code:

let xhr = new XMLHttpRequest();
let form = new FormData();

form.append('file', file, file.name); // the file is loaded correctly
form.append('payload', JSON.stringify(data)); // data is just a JSON object

xhr.onreadystatechange = function() { 
     if (xhr.readyState === XMLHttpRequest.DONE) {
         // we arrive here both on Debian and Windows 10
     }
} 
xhr.upload.onerror = function() { .... } // no error

xhr.open('POST', 'http://<my_url>', true);

console.log(file.type);
xhr.overrideMimeType("text/csv");

xhr.send(form);

A couple of notes:

  • console.log(file.type) actually prints "text-csv" but only in Chrome for Linux (Debian specifically). in the other cases (any other browser or platform) nothing is printed
  • given the previous point, it seems clear to me for some reason any other browser / platform can't recognize the file type, so the file is sent as octet-stream (general binary file)

回答1:


xhr.overrideMimeType changes the MIME-type of the response, not the request.

I you want to change the MIME-type of the file, just create a new Blob with an explicit file type:

var blob = new Blob([blob], {type: 'text/csv'});
form.append('file', blob, file.name);

The above changes the MIME-type of the file in the uploaded form to "text/csv", as desired.

PS. If you literally want to change the MIME-type of the whole request (instead of just the file), use xhr.setRequestHeader('Content-Type', 'custom MIME type here');. (This only makes sense if you are sending a non-standard or custom data in the xhr.send method).



来源:https://stackoverflow.com/questions/40934531/how-to-use-xhr-overridemimetype-in-chrome-ie-edge

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!