Chapter 5. Dealing with Files

When you are building a Backbone application you will consume resources from a RESTful web service; however most of the RESTful services use the JSON format to encode information, but JSON is not suitable to send and receive files. How we can send files to a RESTful server?

If you are developing an application that is not JavaScript–intensive, you can send files through an HTML form, but in Single Page Applications (SPA) this is not the best way to do it. Another issue is that Backbone does not provide an easy mechanism to send files because it is not compatible with the RESTful specification.

But web applications need to work with files. There are some approaches to deal with this common issue. For example, you could use a traditional POST form on resources where files may be included; however, that's not a good option. In this chapter you will learn the following:

  • Handle file uploads from an Express server
  • Adopt strategies to send files to a RESTful server
  • Upload files
  • Create a resource that includes a file in it

We will start by adding support for uploading files to an Express server because it is important to know how a server can respond to upload requests.

Express server

To demonstrate how to send files to a server, in this chapter we will work with the latest version of Express (the latest version available at the time of writing is Express 4.x). The server will be responsible for storing the REST resources and handling file uploads. Please consult the GitHub repo for this book to get the implementation of the server for the previous chapters.

For now, the current server is able to create, get, update, and delete contact resources; we need to add a mechanism to upload an avatar image for a contact. For simplicity the application does not use a database to store its data, but instead uses a hash table to store all data in memory. For example, the next snippet demonstrates how to store a contact:

// Insert a new contact JSON into the contacts array
createContact(req, res) {
var contact = extractContactData(req);

  // Asssign a random id
  contact.id = makeId();
contacts.push(contact);

res.status(201)
.json(contact);
}
..................Content has been hidden....................

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