使用 XMLHttprequest 上传文件 - multipart/form-data 中缺少边界 [英] Uploading a file with XMLHttprequest - Missing boundary in multipart/form-data

查看:63
本文介绍了使用 XMLHttprequest 上传文件 - multipart/form-data 中缺少边界的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 XMLHttprequest 上传文件.这是上传文件的JS函数:

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);
}

在服务器端,在 upload.php 我这样读取文件:

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

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

一切正常,除了我收到一个 PHP 警告:

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

第 0 行 Unknown 中的 multipart/form-data POST 数据中缺少边界.

如果我删除此行:xhr.setRequestHeader("Content-Type", "multipart/form-data");警告消失了.

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

这里应该是什么问题?

推荐答案

这对我来说有点奇怪,但这确实有效:

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);

在这种情况下,在服务器端我不会读取通过 php://input 发送的文件,但该文件将位于 $_FILES 数组中.

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.

这解决了我的问题,但我仍然很好奇为什么现在出现在 $_FILES 中的文件?

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

在 Chrome、Mozilla、Safari 和 IE10 中测试.

Tested in Chrome, Mozilla, Safari, and IE10.

这篇关于使用 XMLHttprequest 上传文件 - multipart/form-data 中缺少边界的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆