Python 通过HttpResponse将Django视图中的PIL图像发送到浏览器进行下载
我正在尝试从Django视图向浏览器发送一个PIL图像,以便自动下载。下面的代码似乎适用于许多人:Python 通过HttpResponse将Django视图中的PIL图像发送到浏览器进行下载,python,django,httprequest,Python,Django,Httprequest,我正在尝试从Django视图向浏览器发送一个PIL图像,以便自动下载。下面的代码似乎适用于许多人: response = HttpResponse(content_type='image/jpg') PIL_imageToSend.save(response, "JPEG") response['Content-Disposition'] = 'attachment; filename="name.jpg"' return response 我通过Ajax调用Django视图,当我打印
response = HttpResponse(content_type='image/jpg')
PIL_imageToSend.save(response, "JPEG")
response['Content-Disposition'] = 'attachment; filename="name.jpg"'
return response
我通过Ajax调用Django视图,当我打印回调时,我会得到看起来像JPEG图像的内容,但不会触发下载。我是否错过了让下载自动触发的内容 更好的/有效的方法是,首先将图像保存到任何位置,然后从那里读取图像以准备如下响应:
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
PIL_imageToSend是自定义函数吗?你试过用这种方法吗?PIL_imageToSend是一个python变量,其中包含了那篇文章中的PIL image实例。看起来他们正在做的事情与我在上面的代码片段中所做的非常相似。不确定下载为什么没有触发。。。但谢谢你的链接:)