HOWTO: Uploading files through REST API?

Hello!    I am building a REST API on top of an application and I wonder how do I manage the file uploads through REST?

In my API, JSON is used for communication. Consider the case of creating a user:

I POST the following JSON to: {"name": "Mohsin", "picture": "/home/mohsin/Pictures/mohsin.jpg"}

like this:

POST /users

Then how do I upload the file?

I know even the question is missing the details like the REST call is not mentioning important HTTP headers, but nonetheless, lets discuss it.

Regards, Mohsin

In this instance you probably have to drop back to a standard postback rather than using JS. Most people using the attachment_fu plugin for handling the file in the controller. For the upload process itself I prefer the "ajax-like" solution that uses the 'respond_to_parent' plugin as described here:

http://khamsouk.souvanlasy.com/2007/5/1/ajax-file-uploads-in-rails-using-attachment_fu-and-responds_to_parent

Well, this can be done without any plug in. I just devised the method of it. First thing is that your post request should have Content-Type set to "Content-Type: multipart/form-data". Now, you should post the request with following parameters in the request header:

person: {"Name": "Mohsin", "Age": 12, "Picture": "picFile"} picFile: --text/binary data of the pic file here --

Now POST all this to /users.

In your controller, parse the incoming JSON resource like this: require 'json' person = JSON.parse(params[:person])

# Now the picture is an IO object! picture = person['Picture'] #rewind this file picture.rewind

# Save the file File.open('/usr/local/uploads/pic.jpg', "wb") do |file|   file.write(picture.read) end

And you are done with the File upload with REST API.