我使用busboy body解析器解析多部分表单数据。因此,我要在req.body中获取名称,用户名键值以及req.files中的文件之类的字段。但是Iam无法使用multer将文件上传到目录中。
app.use(busboyBodyParser());
app.post('/createUser', (req, res) => {
console.log(req.body);
console.log(req.files);
const storage = multer.diskStorage({
destination: './public/uploads/',
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now() +
path.extname(file.originalname));
}
});
const upload = multer({
storage: storage
}).single(req.files['uploadpic']);
upload(req, res, (err) => {
});
});
答案 0 :(得分:0)
您无需将busboy
与multer
一起使用,因为它是基于upload.single('fieldName') //is the syntax for single file
构建的。
您的文件未保存,因为您的文件采用数组形式,但是您尝试使用错误的语法将其作为单个文件读取。
//removing busbodyparser
//declaring multer configs
const storage = multer.diskStorage({
destination: './public/uploads/',
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now() +
path.extname(file.originalname));
}
});
const upload = multer({
storage: storage
}).array('uploadpic', 8]
//make sure you define maxCount - here 8 is given as an example
//array will take in a number of files with the same 'uploadpic' field name
app.post('/createUser', (req, res) => {
upload(req, res, function(err) {
if (err) {
//show error
}
//your files are saved and req.body and req.files are populated using multer
console.log(req.files);
console.log(req.body);
});
});
您的代码将被这样重写:
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>plz work</title>
</head>
<body>
<img style="max-width:100%" src="//cdn.thinglink.me/api/image/1093320091384152066/1024/10/scaletowidth#tl-1093320091384152066;'" class="alwaysThinglink" />
<script async charset="utf-8" src="//cdn.thinglink.me/jse/embed.js"></script>
</body>
</html>