从Amazon S3使用Django下载文件 [英] Download files from Amazon S3 with Django
问题描述
我有一个Django应用程序,允许用户下载他们购买这些MP3文件都托管在Amazon S3中的MP3文件。我怎么能强制下载,当用户点击下载按钮,而不让他们看到(亚马逊)原始链接? 我有一个观点,即下载该文件,但该文件已损坏。 下面是它的样子:
高清下载(要求):
文件名='https://s3-eu-west-1.amazonaws.com/skempi/Ihsahn/04-emancipation-qtxmp3.mp3
响应= Htt的presponse(MIMETYPE ='应用/武力下载)
响应['内容处置'] ='附件;文件名=%S%文件名
响应[X-SENDFILE] =文件名
返回响应
我不容易找到指定如何做到这一点,最终回到这个问题一次又一次,当我搜索的任何地方。因此,
通过使用博托后端Django的仓库,要做到这一点的方式是一样的东西。
文件路径= settings.MEDIA_DIRECTORY + file.name
response_headers = {
响应内容类型:应用/武力下载,
响应内容处置:附件;文件名=%S'%file.name
}
URL = s3.generate_url(60,GET,
斗= settings.AWS_STORAGE_BUCKET_NAME,
键=文件路径,
response_headers = response_headers,
force_http =真)
返回http.Htt presponseRedirect(URL)
I have a Django app that allows users to download MP3 files that they purchased and these MP3 files are hosted in Amazon S3. How can I force a download when users click a "download" button without allowing them to see the original link (to Amazon)? I have a view that downloads the file but the file is corrupt. Here is how it looks like:
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
I couldn't easily find anywhere that specified how to do this and ended up back at this question time and again when I searched. So
With django-storages using the boto backend, the way to do this is something like
filepath = settings.MEDIA_DIRECTORY + file.name
response_headers = {
'response-content-type': 'application/force-download',
'response-content-disposition':'attachment;filename="%s"'%file.name
}
url = s3.generate_url(60, 'GET',
bucket=settings.AWS_STORAGE_BUCKET_NAME,
key=filepath,
response_headers=response_headers,
force_http=True)
return http.HttpResponseRedirect(url)
这篇关于从Amazon S3使用Django下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!