首页 > 解决方案 > 如何将图像插入 CouchDB

问题描述

我试图弄清楚如何使用此处找到的 node-CouchDB 库将图像插入 CouchDB:https ://www.npmjs.com/package/node-couchdb

这是我所做的:

fs.readFile('download.jpeg', (err, data) => {
        binary_data = new Buffer(data, 'binary');
        couch.insertAttachment("node_db", doc_number, "download.jpeg", binary_data, rev_number).then(({data, headers, status}) => {

        }, err => {
            console.log("ERROR"+ err.code);
        });
});

结果是 CouchDB 将其存储为文档格式,如下所示:

{
  "_id": "2741d6f37d61d6bbdf63df3be5000504",
  "_rev": "22-bfdbe6db35c7d9873a2cc8a38afb2833",
  "_attachments": {
    "attachment": {
      "content_type": "application/json",
      "revpos": 22,
      "digest": "md5-on0A+d7045WPI6FyS1ut4g==",
      "length": 22482,
      "stub": true
    }
  }
}

//This is what the data looks like in CouchDB using the View Attachment Function through the interface:

{"type":"Buffer","data":[255,216,255,224,0,16,74,70,73,70,0,1,1,0,0,1,0,1,0,0,255,219,0,132,0,9,6,7,18,18,18,21,18,19,19,22,21,21,23,23,23,24,21,21,21,23,23,21,21,24,21,21,21,23,22,22,21,21,22,24,29,40,32,24,26,37,29,21,21,33,49,33,37,41,43,46,46,46,23,31,51,56,51,45,55,40,45,46,43,1,10,10,10,14,13,14,26,16,16,26,45,37,29,37,45,45,45,45,45,45,45,241,...]

然后我尝试在请求的标头中将 Content-Type 属性更改为“image/jpeg”,结果是:

{
  "_id": "2741d6f37d61d6bbdf63df3be5000504",
  "_rev": "23-cf8c2076b43082fdfe605cad68ef2355",
  "_attachments": {
    "attachment": {
      "content_type": "image/jpeg",
      "revpos": 23,
      "digest": "md5-SaekQP37DCCeGX2M8UVeGQ==",
      "length": 22482,
      "stub": true
    }
  }
}

但是,这仍然会导致无法从 CouchDB 界面查看图像(单击查看附件)。在这种情况下,图像的大小仅为 6,904 字节,但它的存储长度约为 22k(增加了 CouchDB 中的大小),所以我假设我没有将图像的正确表示(编码)传递给 CouchDB .

标签: node.jscouchdbnode-modules

解决方案


您可以将图像数据编码为 base64 字符串并保存,尽管我根本不推荐它。我要做的是将文件上传到 AWS S3 之类的对象存储或它的开源替代 MinIO,然后将文件的引用(例如图像 URL)保存在数据库中。

PS:对不起,我的答案中缺少链接和参考,我正在手机上写。我一回家就可以编辑它并包含参考资料。


推荐阅读