python HttpResponse下载多张图片
时间: 2023-11-12 13:24:37 浏览: 168
您可以使用Django的HttpResponse来下载多张图片。以下是示例代码:
```python
import os
import io
from django.http import HttpResponse
def download_images(request):
image_paths = ['/path/to/image1.jpg', '/path/to/image2.jpg', '/path/to/image3.jpg']
# create a file-like buffer to receive data
zip_buffer = io.BytesIO()
# create a zip file with the images
with zipfile.ZipFile(zip_buffer, mode='w') as zip_file:
for image_path in image_paths:
# get the file name from the path
file_name = os.path.basename(image_path)
# add the image to the zip file
zip_file.write(image_path, file_name)
# seek to the beginning of the buffer
zip_buffer.seek(0)
# set the content type and attachment header
response = HttpResponse(zip_buffer, content_type='application/zip')
response['Content-Disposition'] = 'attachment; filename="images.zip"'
return response
```
在这个例子中,我们使用Python的内置zipfile模块将多张图片打包成一个zip文件。然后,我们创建一个HttpResponse对象,并将打包好的zip文件作为响应内容。最后,我们设置响应头,使浏览器将响应内容作为附件下载。
阅读全文