Attaching a file into a resource

Before we start receiving files in the Express server, we need to set up a strategy for that. We still want to use the RESTful services, so changing the format of the transmission data is not an option.

Respecting the RESTful standard (for more on the REST design for file uploads, see http://bit.ly/1GXqPNY), we can attach a subresource endpoint under the target resource to handle the uploads, so that it will not disturb the original resource. However, this approach has a limitation: the resource should exist first, which means that you cannot create a contact and its avatar photo at the same time.

Following this approach, the endpoint for the avatar file uploading can be located at:

http://example.com/api/contacts/10/avatar
Attaching a file into a resource

Figure 5.1 File uploading schema

The preceding figure shows the schema for how file uploading should be handled by the server; the avatar endpoint will handle POST requests encoded as multipart/form-data instead of JSON, because that's the only way to upload files using the HTTP protocol. Note that in the endpoint it's included the contact id; in this way, once the file is uploaded we can associate the file with the resource. Though the endpoint does not accept a JSON as input, it can return a JSON to inform about the process:

{
  "success": true,
  "avatar": {
    "file": "something.jpg",
    "url": "http://example.com/avatar/something.jpg"
  }
}

In this example result, the server is telling us that we can access the avatar through the http://example.com/avatar/something.jpg URL. We need to modify the contact resource to include this new information in it:

{
  "name": "John Doe",
  "email": "[email protected]",
"avatar": {
    "file": "something.jpg",
    "url": "http://example.com/avatar/something.jpg"
  }

}

The contact resource now includes the avatar information so that it can be used to show the avatar wherever it's needed—for example, in the contact list. To display the avatar image, the only thing you need to do is include the avatar URL in an img tag.

The server should be able serve these files too. In the simplest workflow, you can put all the avatar images in a common path and serve that path as regular assets; the downside of this approach is that anyone can see the files if they have the name of the file.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.211.106