How to allow binary download using the GRAPE API

I want to allow the download of a binary file (.p12 file) using the ruby ​​Grape API. This is what I'm trying.

get '/download_file' do pkcs12 = generate_pkcsfile content_type('application/octet-stream') body(pkcs12.der) end 

Equivalent code with ActionController

 begin pkcs12 = generate_pkcsfile send_data(pkcs12.der, :filename => 'filename.p12') end 

The problem is that the file downloaded using the API seems to be a text file with the prefix '\ ufffd' embedded for each character, while the file downloaded using the browser seems to be binary. How to use the GRAPE API to allow the download of the same file that is loaded through the ActionController send_data p>

+4
source share
2 answers

There are problems # 412 and # 418 have been reported on the grape github page. Which is related to returning the binary file and overriding the content type.

To return the binary format:

 get '/download_file' do content_type "application/octet-stream" header['Content-Disposition'] = "attachment; filename=yourfilename" env['api.format'] = :binary File.open(your_file_path).read end 
+12
source

I think your Grape code is fine, I tested it with a browser and the Mac HTTP tool (called GraphicalHTTPClient), which I use to test the API. I successfully downloaded the binary from disk and passed it with the MIME type 'application/octet-stream' using an almost identical code for yours:

  get :download do data = File.open('binary_data').read content_type 'application/octet-stream' body data end 

I suggest your problem with the API client and / or character encoding (as Stuart M suggests). Although another possibility that arises for me is our discussion so far, that some rack middleware does not start correctly and modifies the output from Grape.

+1
source

Source: https://habr.com/ru/post/1481682/


All Articles