使用XMLHttpRequest将多个文件上传到Express.js 3.5服务器 [英] Upload multiple files with XMLHttpRequest to Express.js 3.5 Server

查看:116
本文介绍了使用XMLHttpRequest将多个文件上传到Express.js 3.5服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



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

问题是通过AJAX上传: req.files 始终为空。



有一些代码:



表单:

 < form action =http:// localhost:3000 / uploadmethod =POSTenctype =multipart / form-dataname =form> 
< input type =filename =uploadsid =filesmultiple =multiple>
< input type =submitname =submitvalue =submit>
< / form>

前端的上传部分(文件[0] .data)是一个文件 - 不是数组或者某事):

  function uploadFiles(files){
var xhr = new XMLHttpRequest();
xhr.submittedData = files; //包含文件的对象数组。但是它不适用于一系列文件,也不适用于一个文件
xhr.onload = successfullyUploaded;
xhr.open(POST,http:// localhost:3000 / upload,true);
xhr.setRequestHeader('X-Requested-With','XMLHttpRequest');
xhr.send();
}

发生问题的后端:

  exports.receiveUpload = function(req,res){
console.log(req.files); //空
var files = req.files.uploads; //始终为空,使用AJAX上传。正常上传它是罚款
console.log(req.xhr); // true
// ...
}

这里有一些Express .js配置(我已经有同样的错误没有AJAX - 在代码中的注释,你可以看到线和Stack Overflow的帖子解决了上传没有AJAX):

  //所有环境
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());

//这3行必须在app.use(app.router)之前
// https://stackoverflow.com/questions/21877098/upload-file-using-express -failed-can not-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')));

提前感谢!





C。

解决方案

Thx to @Pengtuzi我解决了:



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



这是为我解决的代码:

  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');
(文件中的var文件){
formData.append(uploads,files [file] .data);
}
xhr.send(formData);
}


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.

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

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

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

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

// 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.

解决方案

Thx to @Pengtuzi I solved it:

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

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

这篇关于使用XMLHttpRequest将多个文件上传到Express.js 3.5服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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