我正在尝试上传一个post request表单的图像。在我的express.js服务器中,我都使用multer和urlencodedParser,因为我通过post请求体传递所有html输入作为json对象,加上一个文件的选择,我正在用multer处理它。
下面是这个表单的HTML代码:<form action="http://localhost:8000/api/addOrgs" method="post">
<div class="form-row">
<!-- OTHER CODE -->
<div class="form-group col-md-6">
<label>Image or Logo</label>
<input type="file" class="form-control" name="image" id="fileToUpload">
</div>
<button class="btn btn-primary"> Add the organization to the system</button>
</div>
</form>
我已经设置了multer:
// add image to folder
var multer = require('multer')
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, '../public/images/')
},
filename: function (req, file, cb) {
cb(null, file.originalname)
}
})
var upload = multer({ storage: storage })
下面是快速post请求处理程序:
// to add a new organization to the list
app.post('/api/addOrgs', upload.single('imageToUpload'), urlencodedParser, (req, res)=> {
try {
var newobj = req.body;
// want to change name of id in obj
// add image name and delete image field
newobj['img'] = newobj.image;
delete newobj.image;
// read orgs file
let orgs = JSON.parse(fs.readFileSync(path.resolve(__dirname, '../orgs.json')));
//... OTHER CODE
// send respond
res.send('<h1>Successfully added!</h1><br><p>'+JSON.stringify(newobj, null, 4)+'</p></br><b>Now you can go <a href="/good">BACK</a></b>')
// OTHER CODE
} catch (e) {
// ... OTHER CODE
}
});
问题是我成功地在通过req发送的json对象中上传了文件的名称。body但是,它不会将文件保存在文件夹中。问题是否来自urlencodedParser
对app.post()
参数的使用?
或者我必须做一些事情,以保存我的app.post()
函数内的文件?
文件的形式应该有enctype="multipart/form-data"
属性。试试这个,它应该可以工作