Tuesday, July 31, 2012

Re: returning a zip file for download

I'm not sure why you're getting a PDF file back, but as for the filename, you can set it using the Content-Disposition header. E.g:

response = return HttpResponse(open(tmp[1]), mimetype="application/zip")
response['Content-Disposition'] = 'attachment; filename="whatever.zip'
return response


_Nik


On 7/31/2012 3:03 PM, Tomas Neme wrote:

Down here's the code in which I'm creating a zip file with a bunch of pdf labels, and returning it on the HttpResponse for the user to DL it.

The weird thing is that I'm getting just a pdf file (ok, I'm testing with a single file, so I don't know if that's the problem) and I can't set the downloaded filename to anything (it's always "download")

Can someone see what I'm doing wrong?

        files = []
        for detail in queryset:
            for parcel in detail.parceldescription_set.select_related().all():
                shipment = parcel.shipment
                if not shipment.label:
                    try:
                        shipment.download_label(args['username'], args['password'])
                    except Shipment.Wait:
                        self.message_user(_("Failed downloading label for "
                                            "shipment {id} because the "
                                            "Canada Post server is busy, "
                                            "please wait a couple of minutes "
                                            "and try again").format(
                            id=shipment.id))
                files.append(shipment.label.file)

        tmp = tempfile.mkstemp(suffix=".zip")
        tf = zipfile.ZipFile(tmp[1], mode="w")
        for file in files:
            filename = os.path.basename(file.name)
            tf.write(file.name, filename)
        tf.close()

        return HttpResponse(open(tmp[1]), mimetype="application/zip")


--
"The whole of Japan is pure invention. There is no such country, there are no such people" --Oscar Wilde

|_|0|_|
|_|_|0|
|0|0|0|

(\__/)
(='.'=)This is Bunny. Copy and paste bunny
(")_(") to help him gain world domination.
--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

No comments:

Post a Comment