django下载zip文件中的图像

时间:2017-11-13 12:23:05

标签: python django python-2.7

我在DJANGO框架中使用此代码可以让一些用户下载图像。 这段代码工作正常,每次下载一些用户下载图像。

但是此代码下载绝对图像我需要将此图像压缩为任何用户下载。

def download_image(request, id):
    product_image=MyModel.objects.get(pk=id)
    product_image_url = product_image.upload.url
    wrapper = FileWrapper(open(settings.MEDIA_ROOT+ product_image_url[6:], 'rb'))
    content_type = mimetypes.guess_type(product_image_url)[0]
    response = HttpResponse(wrapper, content_type=content_type)
    response['Content-Disposition'] = "attachment; filename=%s" % product_image_url
    return response

很容易更改此代码以下载zip文件中的图像吗?

1 个答案:

答案 0 :(得分:3)

尝试以下方法:

def download_image(request, id):
    product_image=MyModel.objects.get(pk=id)
    product_image_url = product_image.upload.url

    image_path = settings.MEDIA_ROOT+ product_image_url[6:]
    image_name = 'whatevername.png'; # Get your file name here.

    with ZipFile('export.zip', 'w') as export_zip:
        export_zip.write(image_path, image_name)

    wrapper = FileWrapper(open('export.zip', 'rb'))
    content_type = 'application/zip'
    content_disposition = 'attachment; filename=export.zip'

    response = HttpResponse(wrapper, content_type=content_type)
    response['Content-Disposition'] = content_disposition
    return response