从Django View发送PIL图像到浏览器,通过HttpResponse下载

问题描述 投票:0回答:1

我正在尝试将一个PIL图像从Django视图发送到浏览器以进行自动下载。以下代码似乎适用于许多人:

 response = HttpResponse(content_type='image/jpg')
 PIL_imageToSend.save(response, "JPEG")
 response['Content-Disposition'] = 'attachment; filename="name.jpg"'
 return response

我通过Ajax调用Django视图,当我打印回调时,我看到的是JPEG图像,但没有触发下载。我错过了让下载自动触发的内容吗?

python django httprequest
1个回答
0
投票

更好/更有效的方法是,首先将图像保存到任何位置,然后从那里读取以准备您的响应,如下所示:

file = open('Read_From_Location/name.jpg', "rb").read()
rea_response = HttpResponse(file, content_type='image/jpeg')
rea_response['Content-Disposition'] = 'attachment; filename={}'.format('name.jpg')
return rea_response
© www.soinside.com 2019 - 2024. All rights reserved.