简体   繁体   中英

Download zip file with Django

I'm quite new on Django and i'm looking for a way to dwonload a zip file from my django site but i have some issue when i'm running this piece of code:

    def download(self):

        dirName = settings.DEBUG_FOLDER

        name = 'test.zip'

        with ZipFile(name, 'w') as zipObj:
            # Iterate over all the files in directory
            for folderName, subfolders, filenames in os.walk(dirName):
                for filename in filenames:
                    # create complete filepath of file in directory
                    filePath = os.path.join(folderName, filename)
                    # Add file to zip
                    zipObj.write(filePath, basename(filePath))

        path_to_file = 'http://' + sys.argv[-1] + '/' + name
        resp= {}

        # Grab ZIP file from in-memory, make response with correct MIME-type
        resp = HttpResponse(content_type='application/zip')
        # ..and correct content-disposition
        resp['Content-Disposition'] = 'attachment; filename=%s' % smart_str(name)
        resp['X-Sendfile'] = smart_str(path_to_file)
        
        return resp

I get:

Exception Value:    
<HttpResponse status_code=200, "application/zip"> is not JSON serializable

I tried to change the content_type to octet-stream but it doesn't work

And to use a wrapper as followw:

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

        # Grab ZIP file from in-memory, make response with correct MIME-type
        resp = HttpResponse(wrapper, content_type=content_type)
        # ..and correct content-disposition
        resp['Content-Disposition'] = content_disposition

I didn't find useful answer so far but maybe I didn't search well, so if it seems my problem had been already traited, feel free to notify me

Thank you very much for any help

You have to send the zip file as byte

response = HttpResponse(zipObj.read(), content_type="application/zip")
response['Content-Disposition'] = 'attachment; filename=%s' % smart_str(name)
return response

I would do like this: (Caveat I use wsl so the python function will make use of cmd lines) In view:

import os
def zipdownfun(request):
    """ Please establish in settings.py where media file should be downloaded from. 
 In my case is media with a series of other folders inside. Media folder is at the same level of project root folder, where settings.py is"""
    file_name = os.path.join(MEDIA_URL,'folder_where_your_file_is','file_name.zip')
    """let us put the case that you have zip folder in media folder"""
    file_folder_path = os.path.join(MEDIA_URL,'saving_folder')
    """The command line takes as first variable the name of the 
    future zip file and as second variable the destination folder"""
    cmd = f'zip {file_name} {file_folder_path}'
    """With os I open a process in the background so that some magic 
       happens"""
    os.system(cmd)
    """I don't know what you want to do with this, but I placed the 
       URL of the file in a button for the download, so you will need 
        the string of the URL to place in href of an <a> element"""
    return render(request,'your_html_file.html', {'url':file_name})

The db I have created, will be updated very often. I used a slightly different version of this function with -r clause since I had to zip, each time, a folder. Why I did this? The database I have created has to allow the download of this zipped folder. This folder will be updated daily. So this function basically overwrites the file each time that is downloaded. It will be so fresh of new data each time.

Please refer to this page to understand how to create a button for the download of the generated file.

Take as reference approach 2. The URL variable that you are passing to the Django template should be used at the place of the file (screenshot attached) I hope it can help! 在此处输入图像描述

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