我有一个 Django 应用程序,允许用户下载他们购买的 MP3 文件,这些 MP3 文件托管在 Amazon S3 中。当用户单击“下载”按钮而不允许他们查看原始链接(到亚马逊)时,我如何强制下载?
我有一个下载文件的 View ,但文件已损坏。
这是它的样子:
def download(request):
filename = 'https://s3-eu-west-1.amazonaws.com/skempi/Ihsahn/04-emancipation-qtxmp3.mp3'
response = HttpResponse(mimetype='application/force-download')
response['Content-Disposition']='attachment;filename="%s"'%filename
response["X-Sendfile"] = filename
return response
最佳答案
如果您不希望文件可下载,请将 ACL 设置为私有(private)(只能通过您的帐户访问)。如果您向他们提供签名 URL,您的用户仍然可以下载文件。签署 URL 时,会生成具有过期时间的 token 。您可以将其设置为合理的 10 分钟。使用Amazon Web Services interface for Python — Boto .
import boto
conn = boto.connect_s3('<aws access key>', '<aws secret key>')
bucket = conn.get_bucket('your_bucket')
s3_file_path = bucket.get_key('path/to/file')
url = s3_file_path.generate_url(expires_in=600) # expiry time is in seconds
return HttpResponseRedirect(url)
请注意,这是安全的,因为 token 仅对一种请求方法(默认为 GET)且仅对一个文件有效。因此,没有人重复使用 token 的风险,例如下载其他文件或操纵给定的文件。
关于django - 使用 Django 从 Amazon S3 下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12975228/