【发布时间】:2017-11-18 22:38:45
【问题描述】:
我有这个视图,它需要一个 user_id 和 image_id。当用户点击链接时,检查是否有图片。如果有,那么我希望文件自动强制下载。
模板:
<a class="downloadBtn" :href="website + '/download-image/'+ user_id+'/'+ image_id +'/'">Download</a>
在我在本地机器上开发它之前,这段代码可以工作。
@api_view(['GET'])
@permission_classes([AllowAny])
def download_image(request, user_id=None, image_id=None):
try:
ui = UserImage.objects.get(user=user_id, image=image_id)
content_type = mimetypes.guess_type(ui.image.url)
wrapper = FileWrapper(open(str(ui.image.file)))
response = HttpResponse(wrapper, content_type=content_type)
response['Content-Disposition'] = 'attachment; filename="image.jpeg'
return response
except UserImage.DoesNotExist:
...
但现在我将 aws s3 用于我的静态和媒体文件。我正在使用 django-storages 和 boto3。如何在浏览器中强制下载图片?
@api_view(['GET'])
@permission_classes([AllowAny])
def download_image(request, user_id=None, image_id=None):
try:
ui = UserImage.objects.get(user=user_id, image=image_id)
url = ui.image.url
...
... FORCE DOWNLOAD THE IMAGE
...
except UserImage.DoesNotExist:
...
... ERROR, NO IMAGE AVAILABLE
...
【问题讨论】:
-
我在 apache2 中使用 xsendfile 做过类似的事情,这有帮助吗?
-
@Ykh 谢谢,但我不太确定。
标签: django amazon-s3 boto3 django-storage