如何解决带有multer的快速上传文件不适用于urlencodedParser
我正在尝试使用发布请求表上传图片。在我的 express.js 服务器中,我同时使用了 multer 和 urlencodedParser,因为我将所有 html 输入作为 json 对象通过 post 请求正文和一个文件的选择传递,我正在使用 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.originalname)
}
})
var upload = multer({ storage: storage })
这是快速发布请求处理程序:
// 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.body 发送的 json 对象中,但 它没有将文件保存在文件夹中。问题是否来自对 urlencodedParser
参数使用 app.post()
?
或者我必须做些什么才能将文件保存在我的 app.post()
函数中?
解决方法
文件的表单应该有 enctype="multipart/form-data"
属性。试试这个,它应该可以工作
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。