Rails [求助] Rails 上传文件到七牛云存储后,怎么再下载到本地?

Sylor-huang · September 24, 2018 · Last by Sylor-huang replied at October 04, 2018 · 1293 hits

我用 Rails 5.2 和 carrierwave-qiniu

现在我可以通过 carrierwave-qiniu 上传文件到服务器,但是我下载时,提示:

Cannot read file 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] = "文件上传失败"
  end
end

def destroy
  @document = Document.find(params[:id])
  @document.destroy
  redirect_to session[:back_path].pop
  flash[:success] = '文件已删除,请重新上传'
end

def download
  @document = Document.find(params[:id])
  response.headers['Content-Type'] = "application/octet-stream"
  response.headers['Content-Disposition'] = "attachment; filename=#{@document.file_name}"
  response.headers['Cache-Control'] =  "private"
  response.headers['X-Accel-Redirect'] = @document.file_name.url
  send_file(@document.file_name.url, disposition: 'attachment')
end

document的 表内容:

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

请问,我该怎么下载远程文件呢?非常感谢。

def download
  @document = Document.find(params[:id])
  redirect_to @document.file_name.url
end

@Rei 非常感谢,我试了 pdf doc xlsl epub chm 格式的文件,除了 pdf,其余的格式都能直接下载。pdf 格式的是在线打开,这是浏览器的问题吧?再次感谢 Rei.

Reply to Sylor-huang

这个,可以在 nginx 配置

@insua 谢谢你的指导,我现在还是在本地呢,还没有上传到服务器。

You need to Sign in before reply, if you don't have an account, please Sign up first.