从附件袋数据库返回网址

Return url from attachment PouchDB

本文关键字:返回 数据库      更新时间:2023-09-26

我正在尝试使用CouchDB和PouchDB创建一个网页。一开始,我创建了一个CouchDB数据库("图像")。在这个数据库中有一个带有多个附件的文档,所有图像(.png)。我能够将CouchDB数据库与PouchDB同步。现在我想使用存储在 PouchDB 中的附件。

我使用 db.get 语句来获取附件。

db.get('image', {attachments: true}).then(function (doc) {
        console.log(doc);
});

现在我想获得不同的图像,因为我需要它们作为不同地方的 src。目前我正在使用:

    db.getAttachment('image', 'image1.png').then(function (blob) {
      var url = URL.createObjectURL(blob);
      console.log('URL image1 created');
    }).catch(function (err) {
        console.log('URL image1 not created');
        console.log(err);
    });

问题是我不知道如何访问创建的网址。我想我必须使用 return 并使用全局变量。但我不知道在这种情况下如何做到这一点。

使用了以下指南,但正如我所说,我想在代码中的其他地方使用 url。

解决方案的一部分

问题似乎是 url 是在 img 标签尝试访问该 url 之后生成的。这意味着即使您正在使用全局变量,您也会收到错误。因此,我更改了顺序。

现在,在生成 url 后,src 会更新。问题仍然是它有点复杂,如果您正在使用多个附件,则不是很有用。我仍然希望获取网址以供进一步使用。

  <body>
     <img id ="test"  alt="Image from DB" style="width:304px;height:228px;">
  <script>
    var url = " ";
    var imageFW = db.getAttachment('image', 'image1.png');
    imageFW.then(function (blob) {
      url = URL.createObjectURL(blob); 
      document.getElementById("test").src = url;
    }).catch(function (err) {
      console.log(err);
    });
  </script>

更新:最后我解决了使用承诺的问题