如何允许使用 GRAPE API 下载二进制文件 [英] How to allow Binary File download using 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 已报告给葡萄 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屋!