适当存储图像

时间:2018-11-24 11:05:27

标签: mysql node.js

我想使用mysqlnodejs存储一些图像。我已经知道将它们直接存储在数据库中不是一个好主意,但是我应该将图像的路径存储在数据库中,并将图像存储在文件系统中。

假设用户上传了一个图像,那么究竟该如何将图像存储在文件系统中?

2 个答案:

答案 0 :(得分:1)

使用multer中间件进行文件上传。

https://www.npmjs.com/package/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:

});
})