【问题标题】:how to store images in the mongodb database as bindata using meteor?如何使用流星将图像存储在 mongodb 数据库中作为 bindata?
【发布时间】:2021-01-06 20:16:01
【问题描述】:

我对使用流星将图像存储在 mongodb 数据库中进行了研究,我发现了这段代码,在存储到数据库之前我被阻止了:

var fs = Npm.require('fs');

// function to encode file data to base64 encoded string
function base64_encode(file) {
  // read binary data
  var bitmap = fs.readFileSync(file);
  // convert binary data to base64 encoded string
  return new Buffer(bitmap).toString('base64');
}

  // convert image to base64 encoded string
  var base64str = base64_encode('Chrysanthemum.jpg');
  console.log(base64str);

问题在于 Npm.require('fs');在客户端不起作用。 如果您对此有解决方案或其他解决方案,例如在流星中工作的插件,并带有关于如何在 mongodb 中存储图像的进度条(对于使用 bindata 的多个图像),请帮助我。提前谢谢你。

【问题讨论】:

    标签: node.js meteor


    【解决方案1】:

    最常见的方法是使用 CollectionFS 使用其内置的 GridFS 功能将数据存储在 Mongo 中。这也可以让您绕过他们的 16mb 文档大小限制。并在客户端和服务器端提供一组各种有用的辅助函数。

    【讨论】:

    • 对于未来的搜索者,请记住,如果您的文档小于 16mb,则您不需要使用 GridFS。您可以将其存储为 base64 字符串,并且(甚至更好)使用 BinData 类型:related question(我自己还在学习这些东西)
    • 另请参阅this comment:“使用 GridFS 存储即使是更小的文件也不会受益。如果您的文件可以存储在 MongoDB 文档中(即 menge.io/2015/03/24/storing-small-images-in-mongodb
    • 如果你能预测到尺寸总是会更小——那么肯定。顺便说一句,CollectionFS 不再维护。现在有更好的选择
    【解决方案2】:
    const mongoose = require("mongoose");
    const { Schema } = mongoose;
    const fs = require('fs');
    const path = require('path');
    
    let uri = "mongodb://localhost:27017/testBin";
    mongoose.connect(uri, {
        useUnifiedTopology: true,
        useCreateIndex: true,
        useNewUrlParser: true
    }).then(async(db) => {
        console.log("connected success");
        const blogSchema = new Schema({
            file: { type: Buffer }
        }, { strict: false });
        const Blog = mongoose.model('mycollection', blogSchema, "mycollection");
        console.log("path.resolve('./index.js') ", path.resolve(__dirname, 'index.js'));
        const file = fs.readFileSync(path.resolve(__dirname, 'index.js'))
        await new Blog({ file }).save()
        mongoose.connection.close()
    
    }).catch(err => {
        console.log(err);
    })
    

    【讨论】:

    • 请不要只发布代码作为答案,还要解释您的代码的作用以及它如何解决问题的问题。带有解释的答案通常更有帮助,质量更高,更有可能吸引投票。
    猜你喜欢
    • 2014-07-02
    • 2018-04-12
    • 2015-08-17
    • 2020-10-17
    • 1970-01-01
    • 1970-01-01
    • 2016-06-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多