首页 > 解决方案 > RoR:如何从 ActiveStorage API 端点下载文件

问题描述

我正在尝试 RoR 来制作 API 休息,我对 ActiveStorage 非常陌生,我能够使用它上传文件。现在我正在努力下载该文件。

我有这个模型:

class Path < ApplicationRecord
  validates :name, presence: true, uniqueness: true
  validates :size, numericality: { greater_than: 0 }, presence: true
  has_one_attached :file_element, dependent: :destroy
end

这个控制器:

class Api::V1::PathsController < ApplicationController
...
def download
   path = User.find(params[:id])
   binary = path.file_element.download
   # stucked here
end
...
end

我不能再进一步了。根据文档,我可以使用下载来获取文件。但我无法让这个工作。

那么,请问,如何从这里继续前进?

标签: ruby-on-railsapirestdownloadrails-activestorage

解决方案


你可以通过发送send_data

send_data(open(path.file_element.url).read, type: path.file_element.content_type)

推荐阅读