在一个用 Rails 编写的 Web 服务中,我想用一个文件和其他信息来回答。
为此,我考虑使用多部分数据进行响应。如何发送包含文件和 json 的多部分响应?
如果有更好的方法来做到这一点,请告诉我。请注意,无法在我发送的文件中添加额外数据。
面对问题加分,即同时发送文件和数据。我已经通过执行多部分请求来实现这一点,但是如果有更好的方法来做到这一点,我想知道。
在一个用 Rails 编写的 Web 服务中,我想用一个文件和其他信息来回答。
为此,我考虑使用多部分数据进行响应。如何发送包含文件和 json 的多部分响应?
如果有更好的方法来做到这一点,请告诉我。请注意,无法在我发送的文件中添加额外数据。
面对问题加分,即同时发送文件和数据。我已经通过执行多部分请求来实现这一点,但是如果有更好的方法来做到这一点,我想知道。
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.
尝试使用 gem 'curb' 或 'rest-client' gem。
和