javascript 使用 XMLHttpRequest 上传多个文件到 Express.js 3.5 服务器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23035977/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 00:13:10  来源:igfitidea点击:

Upload multiple files with XMLHttpRequest to Express.js 3.5 Server

javascriptnode.jsfile-uploadexpressxmlhttprequest

提问by lehnerchristian

I'm trying to build a file uploader with the native FileAPI in JavaScript and I want to upload the files via XMLHttpRequest (without jQuery) to a Node.js server, which uses Express.js.

我正在尝试使用 JavaScript 中的本机 FileAPI 构建文件上传器,我想通过 XMLHttpRequest(不带 jQuery)将文件上传到使用 Express.js 的 Node.js 服务器。

The file reading part works fine and when I upload the file without the XMLHttpRequest it works perfectly (the files are in req.filesin Express.js).

文件读取部分工作正常,当我上传没有 XMLHttpRequest 的文件时,它工作正常(文件在 Express.js中的req.files中)。

The problem is the upload via AJAX: req.filesis always empty.

问题是通过 AJAX 上传:req.files总是空的。

Heres some code:

继承人一些代码:

The form:

表格:

<form action="http://localhost:3000/upload" method="POST" enctype="multipart/form-data" name="form">
  <input type="file" name="uploads" id="files" multiple="multiple">
  <input type="submit" name="submit" value="submit">
</form>

The upload part in the frontend (in files[0].data is a file - not an array or something):

前端的上传部分(在 files[0].data 中是一个文件 - 不是数组或其他东西):

function uploadFiles(files) {
    var xhr = new XMLHttpRequest();
    xhr.submittedData = files; // Array of objects with files included. But it neither works with an array of files nor just one file
    xhr.onload = successfullyUploaded;
    xhr.open("POST", "http://localhost:3000/upload", true);
    xhr.setRequestHeader('X-Requested-With','XMLHttpRequest');
    xhr.send();
}

The backend where the problem occurs:

出现问题的后端:

exports.receiveUpload = function(req, res){
    console.log(req.files); // empty
    var files = req.files.uploads; // always empty with AJAX upload. with normal upload it's fine
    console.log(req.xhr); // true
    // ...
}

And here's some Express.js config (I already had the same error without AJAX - in the comments in the code you can see the lines and the Stack Overflow post that solved it for the upload without AJAX):

这是一些 Express.js 配置(我在没有 AJAX 的情况下已经遇到了同样的错误 - 在代码的注释中,您可以看到在没有 AJAX 的情况下为上传解决了该问题的行和 Stack Overflow 帖子):

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());

// this 3 lines have to be before app.use(app.router)
// https://stackoverflow.com/questions/21877098/upload-file-using-express-failed-cannot-read-property-of-undefined
app.use(express.multipart());
app.use(express.bodyParser({ keepExtensions: true, uploadDir: path.join(__dirname, 'public', 'uploads') }));
app.use(express.methodOverride());


app.use(app.router);
app.use(require('less-middleware')(path.join(__dirname, '/public')));
app.use(express.static(path.join(__dirname, 'public')));

Thanks in advance!

提前致谢!

Regards,

问候,

C.

C。

回答by lehnerchristian

Thx to @Pengtuzi I solved it:

感谢@Pengtuzi 我解决了它:

I used the FormData API to upload the files. My mistake was that I thought the error would happen on the server.

我使用 FormData API 上传文件。我的错误是我认为错误会发生在服务器上。

Here's the code that solved it for me:

这是为我解决它的代码:

function uploadFiles(files) {
    var xhr = new XMLHttpRequest();
    var formData = new FormData();
    xhr.onload = successfullyUploaded;
    xhr.open("POST", "http://localhost:3000/upload", true);
    xhr.setRequestHeader('X-Requested-With','XMLHttpRequest');
    for(var file in files) {
        formData.append("uploads", files[file].data);
    }
    xhr.send(formData);
}