我想使用mysql
和nodejs
存储一些图像。我已经知道将它们直接存储在数据库中不是一个好主意,但是我应该将图像的路径存储在数据库中,并将图像存储在文件系统中。
假设用户上传了一个图像,那么究竟该如何将图像存储在文件系统中?
答案 0 :(得分:1)
使用multer中间件进行文件上传。
答案 1 :(得分:0)
: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-file-upload
const fileUpload = require('express-fileupload');
expressApp.use(fileUpload());
然后在您的路线上
app.post('/upload', function(req, res) {
console.log(req.files.foo); // the uploaded file object
});
我也使用“锐利”来调整图像大小:
https://www.npmjs.com/package/sharp
示例(我尚未测试此代码,只是复制并从项目中更改了一点):
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:
});
})