app.post("/", upload.single("avatar"), function(req, res, next){
var writestream = gfs.createWriteStream({
filename: req.file.filename
});
fs.createReadStream("./uploads/kkm/" + req.file.filename)
.on("end", function() {
fs.unlink("./uploads/kkm/"+ req.file.filename, function(err) {
res.send("success")
})
})
.pipe(writestream);
});
我想将2张图片上传到mongodb,我可以为一张图片创建写入和读取流,但却失去了对两个文件的想法。
我可以管道一张图片而不是两张图片。当我尝试数组方法时,它会回复
" TypeError:无法读取属性' filename'未定义" ERROR。
我的目标是通过一种方法或一次性将两个文件上传到mongodb。我怎样才能做到这一点?
答案 0 :(得分:1)
GridFS方法每次调用插入一个文件,但您可以轻松实现。您需要在Node.JS应用程序中使用循环并将文件逐个发送到GridFS。
如果你使用multer,你可以做这样的事情
const storage = multer.diskStorage({
destination: (req, file, callback) => {
callback(null, './.temp/uploads');
},
filename: (req, file, callback) => {
callback(null, file.fieldname + '-' + Date.now());
}
});
const multerOptions = {
storage: storage
};
const upload = multer(multerOptions).array('files[]');
module.exports = (req, res, next) => {
upload(req, res, (err) => {
for (let i in req.files) {
const file = req.files[i];
// here you can call GridFS method and upload the file
}
});
});
答案 1 :(得分:0)
app.post('/upload', function(request, response) {
upload(request, response, function(err) {
var files = new Array (req.file.filename,req.file.namedName)
for(var i = 0 ; i < files.length; i++)
{
// here you can call GridFS method
}
});