Rails 5下载文件并显示错误:无法读取文件http://xxx/xxx.pdf

时间:2018-09-24 14:36:25

标签: download ruby-on-rails-5

我使用Rails 5.2Carrierwave-qiniu上传和存储文件。

下载文件时,无法直接下载文件,并显示错误:

Cannot read file http://pczd3l6pu.bkt.clouddn.com/document/129/railsguides-5.0.2.1.pdf

但是,我可以使用URL预览Chrome中的文件内容:

http://pczd3l6pu.bkt.clouddn.com/document/129/railsguides-5.0.2.1.pdf

整个错误如下:

Processing by DocumentsController#download as HTML
  Parameters: {"id"=>"129"}
  User Load (0.3ms)  SELECT  `users`.* FROM `users` WHERE `users`.`id` = 2 LIMIT 1
  Document Load (0.3ms)  SELECT  `documents`.* FROM `documents` WHERE `documents`.`id` = 129 LIMIT 1
Sent file http://pczd3l6pu.bkt.clouddn.com/document/129/railsguides-5.0.2.1.pdf (0.3ms)
Completed 500 Internal Server Error in 4ms (ActiveRecord: 0.7ms)



ActionController::MissingFile - Cannot read file http://pczd3l6pu.bkt.clouddn.com/document/129/railsguides-5.0.2.1.pdf:
  app/controllers/documents_controller.rb:35:in `download'

我的document_controllers是这样的:

def create

  @document = Document.new
  @document.file_name = params[:file]
  if @document.file_name.blank?
    render json: { ok: false }, status: 400
    return
  end

  @document.user_id = current_user.id
  if @document.save
    render json: { url: @document.file_name.url, id:@document.id }
  else
    flash[:warning] = "Upload Failed"
  end
end

def destroy
  @document = Document.find(params[:id])
  @document.destroy
  redirect_to session[:back_path].pop
  flash[:success] = 'Please upload files again'
end

def download
  @document = Document.find(params[:id])
  send_file(@document.file_name.url, disposition: 'attachment')
end

我的migration文档:

def change
    create_table :documents do |t|
      t.string :file_name
      t.string :file_type
      t.integer :user_id

      t.timestamps
    end
    add_index :documents, [:user_id, :created_at]
  end

我的routes.rb是这样的:

resources :documents, only: [:create,:destroy] do
    member do
      get :download
    end
  end

如何直接下载文件?非常感谢。

0 个答案:

没有答案