【问题标题】:PouchDB returning wrong image attachment typePouchDB 返回错误的图像附件类型
【发布时间】:2019-10-19 21:28:35
【问题描述】:

我正在尝试让 PouchDB 返回一个小图像附件。当我通过 Fauxton 上传图片时,我的应用程序成功返回了一个带有 type: 'image/svg+xml' 的 Blob,该 Blob 在我的 <img> 元素中正确呈现(使用 URL.createObjectURL)。

但是,如果我让用户上传图像,然后将文件 Blob 放入我的远程 Pouch 数据库,我就会遇到问题。在这种情况下,PouchDB.getAttachment() 现在返回带有 type: 'application/octet-stream' 而不是 'image/svg+xml' 的 Blob,尽管已使用正确的 content_type 上传它。此图像不呈现,给了我一个通用的浏览器 img 占位符。

为什么会发生这种情况?

第 1 步这是我从用户那里检索图像的方法:

var image = new Blob([fs.readFileSync(fileLocation, 'utf-8')], {
   type: 'image/svg+xml'
})

第 2 步这是我将文档(和附件)放入 PouchDB 的方式:

var doc = await PouchDB.get(docID, {attachments: true})
doc._attachments = {
    'logo.svg': {
        content_type: 'image/svg+xml',
        data: image
    }
}
await PouchDB.put(doc)

【问题讨论】:

  • 如何将附件放到数据库中?
  • 谢谢,我已经更新了帖子来回答这个问题。

标签: javascript electron blob pouchdb


【解决方案1】:

您在读取文件时遇到了 2 个问题。首先是您不能将二进制数据视为 UTF8(对于 SVG 文件可能不是真正的问题,但对于其他图像肯定是),其次是您必须对其进行 base64 编码。

base64 编码 blob 有许多不同的方法,但最简单的解决方案是将其放置方法从 put 更改为 putAttachment。像这样的:

HTML:

...
<input type="file" id="inputFile">
...

JS:

...
var inputFile = document.querySelector('#inputFile');
var file = inputFile.files[0];
db.putAttachment('mydoc', 'myfile', file, file.type).then(...)
...

【讨论】:

  • 非常感谢您的回复。现在由于某种原因,我在使用putAttachment 而不是标准put() 时遇到了更新冲突。有什么想法吗?
  • 我认为您需要在更新时更改 doc._rev...db.putAttachment('mydoc', 'myfile', rev_id, file, file.type)
猜你喜欢
  • 2016-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多