如何使用Express 4和Multer保存文件?

时间:2016-09-27 14:30:10

标签: javascript node.js express xmlhttprequest multer

我试图从FormData xhr请求中保存传入的文件,但我甚至无法解析传入的请求。这就是我尝试发送文件的方式:

...
    let xhr = new XMLHttpRequest(),
    formData = new FormData();

    for(let i = 0; i < this.files.length; i++) {
        formData.append(this.files[i], this.files[i].name);
    }
    xhr.open('POST', URL, true);
    xhr.send(formData);
...

这就是我试图抓住它的方式:

var express = require('express');
var router = express.Router();
var multer  = require('multer');
var uploads = multer({dest: './uploads/'});

router.post('/upload', uploads.any(), function (req, res) {
    console.log(req.files); // []
    console.log(req.file); // undefined
    console.log(req.body); //{ '[object File]': '20160715_104330.jpg' }
});

图像出现在服务器上,但没有写入目录上传。

如何在目录上传中保存图像?

1 个答案:

答案 0 :(得分:1)

我发现了错误。以下是更正后的代码行:

formData.append( 'Choose your Fieldname', this.files[i], this.files[i].name);

我只需要将第一个参数放在表示字段名的字符串中。

查看后端的结果:

var express = require('express');
var router = express.Router();
var multer  = require('multer');
var uploads = multer({dest: './uploads/'});

router.post('/upload', uploads.any(), function (req, res) {
    console.log(req.files); 
    /* [ { fieldname: 'Choose your Fieldname',
           originalname: '20160715_104330.jpg',
           encoding: '7bit',
           mimetype: 'image/jpeg',
           destination: './uploads/',
           filename: '72b7a52101537ab1006f4feb0fa752be',
           path: 'uploads\\72b7a52101537ab1006f4feb0fa752be',
           size: 233509 } ]
     */
    console.log(req.file); // undefined
    console.log(req.body); //{}
});

下面是前端中较小的代码:

...
    upload(){
        let xhr = new XMLHttpRequest(),
        formData = new FormData();
        formData.append('Choose your Fieldname', this.files[0], this.files[0].name);
        xhr.open('POST', URL, true);
        xhr.send(formData);
    }
...