【问题标题】:django download images in zip filedjango 下载 zip 文件中的图像
【发布时间】:2017-11-13 12:23:05
【问题描述】:

我在 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 文件中的图像是否容易?

【问题讨论】:

  • 您可以使用压缩文件的python库,然后将该文件作为HttpResponse返回:)
  • @mohammedqudah 怎么样?第一次使用下载

标签: python django python-2.7


【解决方案1】:

尝试以下方法:

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

【讨论】:

  • 看起来不错,但在我的情况下不适合我
  • 为什么?每次请求只需要压缩一张图片吗?
  • 在这种情况下是的,我需要一张图片must be string, not instance 错误消息
  • 我已经根据您的代码编辑了答案,并使用了可以轻松将单个文件添加到 ZIP 文件的模块。
  • 需要write的第二个参数,即ZIP文件内的文件路径。例如,如果您将其称为 export_zip.write(image_url, 'myimage.png'),它将创建一个没有目录的 zip,并在其中创建一个名为 myimage.png 的文件。当然,您需要将图像名称更改为适合您情况的任何名称。
猜你喜欢
  • 1970-01-01
  • 2015-10-18
  • 2020-10-26
  • 1970-01-01
  • 1970-01-01
  • 2015-10-25
  • 2020-03-22
  • 2015-04-30
  • 2019-12-14
相关资源
最近更新 更多