Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multipart response for web service

In one web service written in Rails, I would like to answer with a file along with additional information.

For this, I consider respond with multipart data. How can I send a multipart response with a file and json?

If there is a better way to do this, please let me know. Note that is not possible add the extra data in the file I'm sending.

Extra points for the face of the problem, that is send a file and data at same time. I already accomplished that by doing a multipart request, but if is there a better way to do this, I would like to know.

like image 711
fotanus Avatar asked Oct 20 '25 15:10

fotanus


1 Answers

I don't know exactly what kind of front end you are using and what your browser compatibility requirements are, or you need the webservice for integration with other apps only, but assuming you are communicating with server over ajax and your app is running in modern browser (or you are allowed to use flash plugin), you can return file contents as base64 encoded string as a part of json response. So in rails controller you would have something like this:

render json: {success: true, file: {name: 'invoice.pdf', data: Base64.encode64(@file.read), extra_info: 'some info'}}

on client side you can process that json, get all the metadata you need from it and also let user save the file to their computer. For that you can use flash plugin or native api implementation

This way you can return couple files with any metadata you want with them to user and on client side user can save files if needed. Also, same webservice can be consumed by other applications as long as they can parse json.

like image 68
Iuri G. Avatar answered Oct 23 '25 04:10

Iuri G.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!