我无法使用Node.js中的Multer选择和上传多个文件。
我能够在不同的练习中上传单个文件而没有任何问题,但是现在我被困在多个上传功能上。
我误会了什么?如何使用户可以选择并上传多个文件?感谢您的帮助。
这是我的表单:
<form class="form" action="/file" method="POST" encType="multipart/form-data">
<div class="box"></div>
<div class="form-group">
<label>
<input type='file' name="upload" class="form-control"/>
</label>
</div>
<input id="submit" type='submit' value="Submit" class="btn btn-primary"/>
</form>
我的后端代码:
const express = require('express');
const bodyParser = require('body-parser');
const fileUpload = require('express-fileupload');
const multer = require('multer')
var fs = require('fs');
// SETUP PACKAGES
const path = require('path');
const app = express();
const upload = multer({ dest: 'uploads' }) ;
// SETUP MIDDLEWARE
app.use(bodyParser.urlencoded({ extended: false }));
app.use(fileUpload());
app.use(express.static(__dirname));
// DECLARE UPLOAD DIRECTORY
const uploadDirectory = __dirname + path.sep + 'uploads'
// DECLARE PROMISES
const writeFile = (name, body) => {
return new Promise((resolve, reject) => {
fs.writeFile(uploadDirectory + path.sep + name, body, (err) => {
if (err) {
console.error(err)
} else {
resolve(name)
}
})
}).then(readFile);
}
const readFile = (file) => {
return new Promise((resolve, reject) => {
fs.readFile(uploadDirectory + path.sep + file, 'utf8', (err, data) => {
if (err) {
console.error(err);
} else {
resolve(data)
}
})
})
}
app.get('/',(req,res) => {
res.sendFile(path.join(__dirname, 'index.html'));
});
app.post('/file', upload.array('upload', 5), (req, res) => {
if(req.files.upload instanceof Array){
for (var i = 0; i < req.files.upload.length; i ++ ){
let name = req.files.upload[i].name;
let data = req.files.upload[i].data;
let write = writeFile(name, data);
console.log(req.files.upload[i].name);
write.then(()=> res.end('fileS uploaded'))
.catch((e)=> res.status(500).send(e.message));
}
}else {
// let name = req.files.upload.name;
// let data = req.files.upload.data;
// writeFile(name, data)
// res.end("file uploaded")
}
});
app.listen(8080)
答案 0 :(得分:0)
您没有在输入代码中使用“多个”属性。如果未指定该字段,则输入字段会将上次上传的文件发送到后端,因此只有一个文件会被上传。