从Amazon S3使用Django下载文件文件、Amazon、Django

2023-09-11 23:43:33 作者:清風挽離人

我有一个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(6​​0,GET,
                斗= settings.AWS_STORAG​​E_BUCKET_NAME,
                键=文件路径,
                response_headers = response_headers,
                force_http =真)
返回http.Htt presponseRedirect(URL)
 
AmazonS3api文档类 Web开发文档类资源 CSDN下载

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)