Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to allow Binary File download using GRAPE API

I want to allow downloading a binary file (.p12 file) using ruby's Grape API. This is what I am trying.

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

The equivalent code using ActionController is

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

The problem is the file downloaded using the API seems to be a text file with a '\ufffd' prefix embedded for every character, whereas the file downloaded using the browser seems to be binary file. How do I use the GRAPE API framework to allow downloading the same file that is downloaded via ActionController's send_data

like image 834
boboverflow Avatar asked May 20 '13 01:05

boboverflow


2 Answers

There are issues #412 and #418 have been reported to grape github page. Which are related to return a binary file and override content type.

To return binary format like so:

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
like image 160
Jason YiZhang Chen Avatar answered Nov 10 '22 03:11

Jason YiZhang Chen


I think your Grape code is OK, I have tested a variant of it using a browser and a Mac HTTP tool (called GraphicalHTTPClient) that I use to test APIs. I successfully loaded a binary file from disk and transferred it with MIME type 'application/octet-stream' using almost identical code to yours:

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

I suggest your problem is with the API client and/or the character encoding (as suggested by Stuart M). Although another possibility that occurs to me form our discussion so far, is that some Rack middleware is being triggered incorrectly, and modifying the output from Grape.

like image 30
Neil Slater Avatar answered Nov 10 '22 05:11

Neil Slater