Storing inline attachments in couchdb using java s

2019-07-29 10:40发布

I want to store inline attachments along with new document. Can any body provide the java script snippet to store inline attachments. And is there any way to provide a key while attaching file.

Thanks in advance

1条回答
Emotional °昔
2楼-- · 2019-07-29 11:20

To begin, read the CouchDB attachments documentation.

For example:

  • In document my_doc
  • To attach a file hello.html
  • With content Hello, world

You encode the content with base64. "Hello world" is "'SGVsbG8gd29ybGQ=".

And you create a document like this:

{ "_id": "my_doc",
, "_attachments":
  { "hello.html":
    { "content_type": "text/html"
    , "data": "'SGVsbG8gd29ybGQ="
    }
  }
}

The only difficult part is base64 encoding. I suggest that you use the base64 script included inside CouchDB.

<html>
  <head>
   <script src="/_utils/script/base64.js"></script>
  </head>
  <body>
   The Base64 of "Hello world" is:
   <script>
    var hello = "Hello world"
    var encoded = Base64.encode(hello)
    document.write(encoded)
   </script>

  <p>

  A document with this attachment is:<br>
  <script>
   var doc = { "_id":"my_doc" }

   doc._attachments = {}
   doc._attachments["hello.html"] = {}
   doc._attachments["hello.html"].content_type = "text/html"
   doc._attachments["hello.html"].data = Base64.encode("Hello world")

   document.write(JSON.stringify(doc))       
  </script>
  </body>
</html>
查看更多
登录 后发表回答