expressApp.post('/submit-form',(req,res)=>{
let f = req.files.profileImage;
//its usually a good idea to rename files uploaded to sth unique using DateTime with their original name (or instead of their original file name)
const fileName = (f.name.substring(0, f.name.lastIndexOf('.')) + '-' + Date.now().toString()).replace(' ','');
const fileFormat = f.name.substring(f.name.lastIndexOf('.'), f.name.length);
const filePath = path.resolve('public/media') + '/' + folder + fileName + fileFormat;
f.mv((err)=>{
if(err)
{
console.log('sth went wrong while uploading image!');
return;
}
//HERE STORE filePath to Database or sth:
});
})
2条答案
按热度按时间j1dl9f461#
使用multer中间件进行文件上传。
https://www.npmjs.com/package/multer
zd287kbt2#
:d除了multer,如果您使用的是express,还可以尝试“express fileupload”。将req.files添加到您的请求中(:d更易于使用imo)
https://www.npmjs.com/package/express-fileupload
https://github.com/richardgirges/express-fileupload/tree/master/example#basic-文件上传
然后在你的路线上:
我还使用“夏普”调整图像大小:
https://www.npmjs.com/package/sharp
示例(我没有测试过这段代码,只是从项目中复制和更改了一点):