简体   繁体   中英

How to download zip file from server side to client side (django to react)

On my django server side, I have a file that downloads some files from s3 and then zips them together. I then want to send that zip file to the client side and download it on client side. However, when ever I try to open the zip file on the client side I get a An error occurred while loading the archive

I am running on Ubuntu 14.04 with a django backend and a react frontend. I tried passing the file as a tar file, but that didn't work either. I have also tried many different ways of passing the zip file to the HTResponse, but I always get the same error. Right now to try to make it work, I am just trying to download a zip file I have downloaded on my local computer.

I have tried a bunch of different content_types from application/zip, to octet/stream and force download.

django backend

zip_path = '/home/konstantin/Downloads/sup.zip'
        content_path = mime.guess_type(zip_path)

        with open(zip_path, 'rb') as zip_file:

            response = HttpResponse(zip_file, content_type='application/zip')
            response['Content-Length'] = str(os.stat(zip_path).st_size)

            response['Content-Disposition'] = 'attachment; filename={}'.format('willthiswork.zip')
            return response

react front end (we have a program that changes python to js). The response of the ajax call is passed directly into this method.

def download(self,url):
        data = __new__(Blob([url], {"type": "octet/stream"}))
        csvURL = window.URL.createObjectURL(data)
        tempLink = document.createElement('a')
        tempLink.href = csvURL
        tempLink.download = 'willthiswork.zip'
        tempLink.click()

Expected result: Zip file downloads on client side and is openable Actual result: Zip file downloads, but cannot be opened.

so I finally figure it out. For some reason all the standard solutions of just passing an a regular httpresponse did not work for me, but this answer worked for me. Why? Idk. but it did.

https://stackoverflow.com/a/29939024/11312013

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM