REST

Leave a comment

Advertisements

Upload file from REST in Ruby on Rail with JSON format

Leave a comment

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.