Download files from Amazon S3 with Django

后端 未结 2 1263
挽巷
挽巷 2020-12-28 21:15

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 \"

2条回答
  •  粉色の甜心
    2020-12-28 22:01

    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)
    

提交回复
热议问题