我设置了我的Rails应用程序,使用this tutorial将文件直接上传到AWS S3,效果很好。现在,我正在使用this SO post中的相同方法处理直接下载文件。当我尝试触发下载时,它会挂起,然后最终返回以下错误:
/ user / doc_uploads / download致命 异常重新进入
下面代码中的puts
显示服务器上的无限循环。我根本不了解这段代码应该如何解决这个问题。请帮忙!
doc_uploads_controller.rb
def get
@doc_download = @user.doc_uploads.find_by_id(params[:id])
if @doc_download
key = @doc_download.file_url.split('amazonaws.com/')[1]
puts key
puts S3_BUCKET_NAME
bucketlink = S3_BUCKET_NAME.object(key).presigned_url(:get, expires_in: 3600)
puts bucketlink
redirect_to bucketlink
else
flash[:error]="Something went wrong."
redirect_to user_dashboard_path
end
end
aws.rb:
Aws.config.update({
region: 'us-east-1',
credentials: Aws::Credentials.new(ENV['AWS_ACCESS_KEY_ID'], ENV['AWS_SECRET_ACCESS_KEY']),
})
S3_BUCKET_NAME = Aws::S3::Resource.new.bucket(ENV['S3_BUCKET_NAME'])
routes.rb中:
get 'user/doc_uploads/download', to: 'doc_uploads#get'
视图:
<% @doc_uploads.each do |doc_upload| %>
...
<%= link_to user_doc_uploads_download_path(id: doc_upload.id), target: '_blank' do %>
<p class="glyphicon glyphicon-download-alt"></p>
<% end %>
...
<% end %>
提前致谢!
答案 0 :(得分:0)
如果您能够在代码中正确获取网址,那么您也可以从该网址中读取图片。
试试这个:
def get
@doc_download = @user.doc_uploads.find_by_id(params[:id])
if @doc_download
data = open(@doc_download.file_url)
send_data data.read, filename: 'filename', stream: 'true', buffer_size: '4096'
else
flash[:error]="Something went wrong."
redirect_to user_dashboard_path
end
end
答案 1 :(得分:0)
找到最近发布的帖子here并让他们的解决方案正常工作,如下:
presigner = Aws::S3::Presigner.new
url = presigner.presigned_url(:get_object, bucket: ENV['S3_BUCKET_NAME'], key: key, expires_in: 3600, response_content_disposition: "attachment").to_s
redirect_to url