使用presigned_url触发S3文件的下载 [英] Triggering download of S3 file with presigned_url

查看:101
本文介绍了使用presigned_url触发S3文件的下载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过Rails应用访问S3服务器上的文件.目前,该应用程序能够通过aws-sdk v2 gem创建presigned_url,然后重定向以显示该文件(我一直在使用图像作为文件).这一切都很好,但我真的想触发该文件的自动下载,而不是简单地在浏览器中显示文件.

I'm attempting to access files on my S3 server via my rails app. Currently the app is able to create a presigned_url through the aws-sdk v2 gem and then redirect to display the file (I've mostly been using images as the file). This all works very well but rather than simply displaying the file in the browser, I would REALLY like to trigger an automatic download of that file.

就重定向而言,我的代码如下:

As it stands with the redirect, my code is as follows:

def get
    asset = current_user.assets.find_by_id(params[:id])

    if asset
        s3 = Aws::S3::Resource.new
        bucketlink = s3.bucket(ENV['S3_BUCKET_NAME']).object(asset.uploaded_file.path).presigned_url(:get, expires_in: 3600)
        redirect_to bucketlink
    else
        flash[:error]="Don't be cheeky!  Mind your own assets"
        redirect_to assets_path
    end
end

任何人都可以给我一个有关如何触发此文件下载的线索吗?预先非常感谢.

Can anyone give me a clue as to how I can trigger a download of this file? Many thanks in advance.

推荐答案

我对ruby一无所知,所以这是一个猜测..但是基于我的专业知识,直接与REST API和快速搜索SDK文档以查找特定字符串I想到了,我想您正在寻找这样的东西:

I know nothing about ruby, so this is something of a guess.. but the based on my expertise working directly with the REST API and a quick search of the SDK docs for a specific string I had in mind, I think you are looking for something like this:

bucketlink = s3.bucket(ENV['S3_BUCKET_NAME']).object(asset.uploaded_file.path).presigned_url(:get, expires_in: 3600, response_content_disposition: 'attachment; filename=myfile.jpg')

&response-content-disposition=value 出现在作为已验证的GET请求的查询字符串,S3将该值作为响应中的Content-Disposition:标头返回. 附件"表示下载,不显示",文件名是浏览器通常使用的文件名,如果显示另存为"提示,则提供默认文件名...因此用户下载的文件名可以不同而不是存储在S3中的文件名. 'attachment;<space>filename=<target-filename>'是单个字符串,您希望将其构建为包含有意义的内容,而不是"myfile.jpg".

When &response-content-disposition=value appears in the query string of an authenticated GET request, S3 returns that value as the Content-Disposition: header in the response. "attachment" means "download, don't display" and the filename is the filename the browser will typically use, or offer as the default if a "save as" prompt is shown... so the filename the user downloads can be different than the filename as stored in S3. 'attachment;<space>filename=<target-filename>' is a single string, which you'll want to build to contain something sensible, rather than "myfile.jpg" of course.

这篇关于使用presigned_url触发S3文件的下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆