Safari 10 on Mac not uploading file in XHR
javascript, safari, xmlhttprequest
Solution
So according to another stackoverflow question, I cant remember which one Safari has a bug that when other browsers do file.toBlob(), safari will do file.toString(). So the workaround would be write your own file to blob function and upload that blob.
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://up-z1.qiniu.com/', true);
var formData;
formData = new FormData();
formData.append('key', file.name);
formData.append('token', acessToken);
formData.append('file', fileToBlob(file));
xhr.onreadystatechange = function (response) {
if (xhr.readyState == 4 && xhr.status == 200 && xhr.responseText != "") {
callback(true,null);
} else if (xhr.status != 200 && xhr.responseText) {
callback(false,null);
}
};
xhr.send(formData);
Problem
I'm using XHR to upload an image to an external server which has CORS enabled. everything works fine in Chrome, Firefox and IE. But using Safari, server response with mime type error. saying the file type is 'application/octet-stream' while it should be 'image/*'. After I disabled mime type checking, safari can upload file but its all 0b empty file. anyone knows why? ``` var xhr = new XMLHttpRequest(); xhr.open('POST', 'http://up-z1.qiniu.com/', true); var formData; formData = new FormData(); formData.append('key', file.name); formData.append('token', acessToken); formData.append('file', file); xhr.onreadystatechange = function (response) { if (xhr.readyState == 4 && xhr.status == 200 && xhr.responseText != "") { callback(true,null); } else if (xhr.status != 200 && xhr.responseText) { callback(false,null); } }; xhr.send(formData); ```