【问题标题】:Can you save a image file as a URL into a database using node js?您可以使用节点 js 将图像文件作为 URL 保存到数据库中吗?
【发布时间】:2020-11-27 06:57:08
【问题描述】:

目前,在我的项目中,我正在使用 multer 将图像文件保存到 MongoDB。我通过将图像转换为 base64 格式然后保存该数据来做到这一点。这可行,但它占用了数据库中的大量存储空间,从而降低了我的应用程序的速度。我想知道是否有办法将文件转换为 URL,然后将该 URL 保存到数据库中。
这会变成这样:iVBORw0KGgoAAAANSUhEUgAAAyAAAAMgCAIAAABU...
变成这样的东西:something.com/imageurl。


这是我当前的代码:
var multer = require("multer");
var upload = multer({ 
    storage: multer.memoryStorage(),
    limits: {fileSize: 1 * 2048 * 2048},
    fileFilter: function fileFilter(req, file, cb){
    if(file.mimetype !== 'image/png' | "image/jpg" | "image/jpeg"){
       return cb(new Error('Something went wrong'), false);
    }
    cb(null, true);
    }
}).fields([{ name: 'fileone', maxCount: 1 }, { name: 'filetwo', maxCount: 1 }]);
module.exports = upload;

app.post("/create",  function(req, res){
upload(req, res, function(err){
    if(err){
        res.render("create", {msg: "Error: Please Keep each file under 1mb and only upload PNG, JPG, or JPEG images"});
    } else{
        var fileOne = req.files["fileone"][0].buffer.toString("base64");
        var fileTwo = req.files["filetwo"][0].buffer.toString("base64");
        var title = req.body.title;
        var newPosts = {title: title, fileOne: fileOne, fileTwo: fileTwo}
        Post.create(newPosts, function(err, newlyCreated){
            if (err){
                console.log(err);
            } else{
                res.redirect("/posts/" + newlyCreated._id);
        }
        });
    }
});

})

【问题讨论】:

    标签: node.js multer uploading


    【解决方案1】:

    您可以将文件保存到磁盘并将文件的路径放入数据库中:

    您可以使用multer.diskStorage,而不是使用multer.memoryStorage

    在您的 upload 方法中,req.files 将包含一个指向路径的数组。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-19
      • 2021-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多