所以,我在nodejs中用multer上传文件时遇到了一个问题。在我第一次尝试后,没有返回,目标文件夹中也没有文件。我记录了正文进行检查,它返回[Object: null prototype] {}
。req.file
的返回是undefined
。
我路由文件:workflow.js
var express = require('express');
var router = express.Router();
const multer = require('multer')
var storage = multer.diskStorage({
destination: function (request, file, callback) {
callback(null, "./public/data/satelliteimage/");
},
filename: function (request, file, callback) {
fileName=file.originalname;
callback(null, file.originalname);
}
});
const uploadDest = multer({storage:storage})
router.get('/', function (req, res, next) {
res.render('workflow');
});
router.post("/uploadSatelliteimage", uploadDest.single("satellitenbildInput"), function (req, res, next) {
console.log(req.file);
console.log(req.body);
res.render('workflow');
})
module.exports = router;
我视图文件:workflow.pug
extends layout
block content
br
br
.container
.row.justify-content-md-center
.col-md-3
.col-md-6
div#form_div_sat.active-form
form(action='/workflow/uploadSatelliteimage' method='post' enctype="multipart/form-data")
label.col-md-4.col-form-label.fw-bolder(for='satellitenbild') Satellitenbild
input#satellitenbildInput.form-control.form-control-lg(type='file' name="satellitenbild" accept="image/png")
button#btn_satellite.btn.btn-primary.mb-2 Weiter
br
br
br
.col-md-3
.row.justify-content-md-center
.col-md-1
.col-md-4
div#form_div_train
form
label.col-md-4.col-form-label.fw-bolder(for='trainModell') Trainiertes Modell
input#trainMod.form-control.form-control-lg(type='file' name="trainModell" accept=" " enctype="multipart/form-data" disabled=true)
button#btn_trainMod.btn.btn-secondary.mb-2.disabled Weiter
.col-md-2
br
br
h3.text-center oder
.col-md-4
div#form_div_untrain
form
label.col-md-4.col-form-label.fw-bolder(for='untrainModell') Nicht-trainiertes Modell
input#untrainMod.form-control.form-control-lg(type='file' name="untrainModell" accept=" " enctype="multipart/form-data" disabled=true)
button#btn_untrainMod.btn.btn-secondary.mb-2.disabled Weiter
br
div#form_div
form
input#testR.form-control(type='text' name="testR", disabled = '')
button.btn.btn-secondary.mb-2(type='submit').disabled AOA berechnen
.col-md-1
block scripts
script(src="/javascripts/workflowJS.js" defer)
我在谷歌上搜索了很多,发现了一些stackoverflow问题,但答案对我没有帮助。我的猜测是,它与body-parser
有关,但这只适用于文本,multer
应该是正确的。或者表单的顺序,body还没有填充?或者完全不同的东西。
我希望在你的帮助下找到解决办法。谢谢!
1条答案
按热度按时间fafcakar1#
上传文件字段的名称在前端和后端必须相同,但此处存在不匹配的情况:
伺服器:
前端:
因此,它们需要匹配的不是
satellitenbildInput
和satellitenbild
,而是:伺服器:
前端:
此外,您似乎正在上传多个文件,但来自不同的字段:
trainModell
和untrainModell
,因此您需要使用.fields
方法,在该方法中,您为每个文件字段提供一个带有文件字段名称的对象,该对象位于数组中,并且文件将存储在req.files
中,因此您的路径应如下所示: