ruby-on-rails - 如何允许使用 GRAPE API 下载二进制文件

标签 ruby-on-rails ruby api actioncontroller grape-api

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

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

使用 ActionController 的等效代码是

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

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

最佳答案

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

像这样返回二进制格式:

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

关于ruby-on-rails - 如何允许使用 GRAPE API 下载二进制文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16641388/

相关文章:

python - 从json中提取某些数据

Ruby-on-Rails:如何在不离开索引的情况下访问创建操作

ruby-on-rails - 如何在 ruby​​ 测试中写出三个变量中至少有一个为空?

ruby-on-rails - recaptcha 配置中的代理是什么?

ruby - Windows Visual Studio 中的 Iron Ruby

mysql - 未初始化常量 MysqlCompat::MysqlRes

python - 如何将事件参数传递给运行以响应 Splunk 警报的 Python 脚本?

python - 外部 API RabbitMQ 和 Celery 速率限制

ruby-on-rails - Rails yield 和 content_for wieird 行为, `yield :filter` 仅在放置在默认 yield 之后才有效

ruby-on-rails - 在 Rails 应用程序中运行 rake 任务