gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 00:34:29 24 4
gpt4 key购买 nike

我正在尝试保存来自 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' }
});

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

如何将图片保存到 uploads 目录中?

最佳答案

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

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

关于javascript - 如何使用 Express 4 和 Multer 保存文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39727385/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com