【问题标题】:Download zip file with Django使用 Django 下载 zip 文件
【发布时间】:2020-10-26 12:51:18
【问题描述】:

我是 Django 的新手,我正在寻找一种从我的 django 站点下载 zip 文件的方法,但是当我运行这段代码时遇到了一些问题:

    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

我明白了:

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

我尝试将 content_type 更改为 octet-stream 但它不起作用

并使用如下包装器:

        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

到目前为止我没有找到有用的答案,但也许我没有很好地搜索,所以如果我的问题似乎已经有特征,请随时通知我

非常感谢您的帮助

【问题讨论】:

  • download() 似乎属于基于类的视图。请发布完整的课程。

标签: python django download zipfile


【解决方案1】:

您必须以字节形式发送 zip 文件

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

【讨论】:

    猜你喜欢
    • 2015-10-18
    • 2015-04-30
    • 1970-01-01
    • 2017-10-22
    • 1970-01-01
    • 1970-01-01
    • 2018-06-10
    相关资源
    最近更新 更多