如何使用GRAPE API允许二进制文件下载 [英] How to allow Binary File download using GRAPE API

查看:141
本文介绍了如何使用GRAPE API允许二进制文件下载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想允许使用ruby的Grape API下载二进制文件(.p12文件).这就是我正在尝试的.

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

使用ActionController的等效代码为

The equivalent code using ActionController is

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

问题在于,使用API​​下载的文件似乎是每个字符都嵌入了'\ ufffd'前缀的文本文件,而使用浏览器下载的文件似乎是二进制文件.如何使用GRAPE API框架来下载与通过ActionController的send_data下载的文件相同的文件

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

推荐答案

存在问题#412 #418 已报告到grape github页面. 与返回二进制文件和覆盖内容类型有关.

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

这篇关于如何使用GRAPE API允许二进制文件下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆