Uploading a file with XMLHttprequest - Missing boundary in multipart/form-data

假装没事ソ 提交于 2019-12-18 04:49:09

问题


I'm uploading a file with XMLHttprequest. Here is the JS function, that uploads a file:

var upload = function(file) {
    // Create form data
    var formData = new FormData();
    formData.append('file', file);

    var xhr = new XMLHttpRequest();

    // Open
    xhr.open('POST', this.options.action);

    // Set headers
    xhr.setRequestHeader("Cache-Control", "no-cache");
    xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
    xhr.setRequestHeader("Content-Type", "multipart/form-data");
    xhr.setRequestHeader("X-File-Name", file.fileName);
    xhr.setRequestHeader("X-File-Size", file.fileSize);
    xhr.setRequestHeader("X-File-Type", file.type);

    // Send
    xhr.send(formData);
}

On the server side, in upload.php I read the file this way:

file_put_contents($filename, (file_get_contents('php://input')));

Everything works fine, except that I get a PHP Warning:

Missing boundary in multipart/form-data POST data in Unknown on line 0.

If I remove this line: xhr.setRequestHeader("Content-Type", "multipart/form-data"); the warning goes away.

What should be the problem here?


回答1:


Well this is strange a little bit for me, but this is what worked:

// Open
xhr.open('POST', this.options.action, true);

// !!! REMOVED ALL HEADERS

// Send
xhr.send(formData);

In this case, on server side I don't read the file sent via php://input but the file will be in the $_FILES array.

This solved my problem, but I'm still curious why appears now the file in $_FILES?

Tested in Chrome, Mozilla, Safari, and IE10.



来源:https://stackoverflow.com/questions/12348216/uploading-a-file-with-xmlhttprequest-missing-boundary-in-multipart-form-data

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