0

I use this code in DJANGO framework to can some user download images. this code work fine and download image every time to press download some user.

but this code download absolute images I need to zip this images for any user download.

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

is easy to change this code to download images in zip file ?

Mar
  • 683
  • 2
  • 11
  • 26

1 Answers1

2

Try the following:

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
Farid Chowdhury
  • 2,766
  • 1
  • 26
  • 21
Daniel
  • 597
  • 6
  • 15
  • look nice but don't wok fir my in my case – Mar Nov 13 '17 at 19:17
  • Why? Do you need to zip only one image per request? – Daniel Nov 13 '17 at 19:30
  • in this case yes I need one image `must be string, not instance` error message – Mar Nov 13 '17 at 19:31
  • I've edited the answer based on your code and using a module that can add a single file to the ZIP file easily. – Daniel Nov 13 '17 at 19:46
  • I change code in `with` because not work in python 2.7 to `with zipfile.ZipFile('export.zip', mode='w') as export_zip: export_zip.write(image_url)` look to work but not correct because in the zip file I have all folders path and finally image for example in .zip file inside I have `C:/user/username/projects/user/myimage.png` but I need to have only the image in .zip file where is wrong in code ? – Mar Nov 13 '17 at 20:39
  • 1
    You need the second parameter to `write`, which is the file path inside the ZIP file. If you call it like `export_zip.write(image_url, 'myimage.png')` for example, it will create a zip with no directory and a file called `myimage.png` inside. Of course you will want to change the image name to whatever makes sense in your case. – Daniel Nov 13 '17 at 22:52
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/158925/discussion-between-mar-and-daniel). – Mar Nov 14 '17 at 06:42