Couchdb 简明教程

CouchDB - Attaching Files

Attaching Files using cURL

你可以像电子邮件一样附加文件到 CouchDB。文件包含元数据,例如名称,以及包含的 MIME 类型和附件包含的字节数。若要将文件附加到文档中,你必须向服务器发送 PUT 请求。以下是要将文件附加到文档中的语法代码:

You can attach files to CouchDB just like email. The file contains metadata like name and includes its MIME type, and the number of bytes the attachment contains. To attach files to a document you have to send PUT request to the server. Following is the syntax to attach files to the document −

$ curl -vX PUT http://127.0.0.1:5984/database_name/database_id
/filename?rev=document rev_id --data-binary @filename -H "Content-Type:
type of the content"

请求具有多种选项,如下所示:

The request has various options that are explained below.

  1. --data-binary@ − This option tells cURL to read a file’s contents into the HTTP request body.

  2. -H − This option is used to mention the content type of the file we are going to upload.

Example

让我们通过向 CouchDB 发送 PUT 请求,将名为 boy.jpg, 的文件附加到数据库中 ID 为 001, 的文档上。在此之前,你必须获取 ID 为 001 的文档的数据,才能获取其当前 rev ID,如下所示:

Let us attach a file named boy.jpg, to the document with id 001, in the database named my_database by sending PUT request to CouchDB. Before that, you have to fetch the data of the document with id 001 to get its current rev id as shown below.

$ curl -X GET http://127.0.0.1:5984/my_database/001
{
   "_id": "001",
   "_rev": "1-967a00dff5e02add41819138abb3284d"
}

现在,使用 _rev 值,向 CouchDB 服务器发送 PUT 请求,如下所示:

Now using the _rev value, send the PUT request to the CouchDB server as shown below.

$ curl -vX PUT http://127.0.0.1:5984/my_database/001/boy.jpg?rev=1-
967a00dff5e02add41819138abb3284d --data-binary @boy.jpg -H "ContentType:
image/jpg"

Verification

若要验证附件是否已上传,请获取文档内容,如下所示:

To verify whether the attachment is uploaded, fetch the document content as shown below−

$ curl -X GET http://127.0.0.1:5984/my_database/001
{
   "_id": "001",
   "_rev": "2-4705a219cdcca7c72aac4f623f5c46a8",
   "_attachments": {
      "boy.jpg": {
         "content_type": "image/jpg",
         "revpos": 2,
         "digest": "md5-9Swz8jvmga5mfBIsmCxCtQ==",
         "length": 91408,
         "stub": true
      }
   }
}

Attaching Files using Futon

Upload Attachment

使用此选项,你可以将新附件(例如文件、图像或文档)上传到数据库。为此,请点击 Upload Attachment 按钮。将出现一个对话框,你可以在其中选择要上传的文件。选择文件,然后点击 Upload 按钮。

Using this option, you can upload a new attachment such as a file, image, or document, to the database. To do so, click on the Upload Attachment button. A dialog box will appear where you can choose the file to be uploaded. Select the file and click on the Upload button.

upload attachment

已上传的文件将显示在 _attachments 字段下。稍后,你可以通过点击该文件来查看该文件。

The file uploaded will be displayed under _attachments field. Later you can see the file by clicking on it.