【问题标题】:How to download a archive using django response?如何使用 django 响应下载档案?
【发布时间】:2021-06-02 17:34:29
【问题描述】:

我想在创建后下载存档。代码如下:

def downloadArchive(room, catalog):
test = RoomTest.objects.get(idRoom=room)
zip_name = room.name + "_" + token_urlsafe(5) + '.zip'
zip_path = 'media/zipFiles/' + zip_name

if test.OLD_Archive != '' and os.path.exists(test.OLD_Archive):  # remove old file.
    os.remove(test.OLD_Archive)

with ZipFile(zip_path, 'w') as zipObj:
    for student in catalog:
        zipObj.write('media/' + str(student.file),
                     student.studentFullName() + os.path.splitext('media/' + str(student.file))[1])

    test.OLD_Archive = zip_path
    test.save()

    response = HttpResponse(zipObj)
    response['Content-Type'] = 'application/x-zip-compressed'
    response['Content-Disposition'] = 'attachment; filename=' + zip_name

    return response

每次我尝试下载时,都会出现错误“存档格式未知或已损坏”。我觉得这条路坏了。任何想法如何检查响应路线?

顺便说一句:如果我手动下载存档(存档后),它工作正常。

【问题讨论】:

    标签: python django archive zipfile


    【解决方案1】:

    解决了,我用过:

    response = redirect('/' + zip_path)
    return response
    

    【讨论】:

    • 您能解释一下这段代码的作用/它如何解决问题吗?
    • @SimonCrane,此代码重定向到存档路径。我不确定它是否可以,但它对我有用。
    猜你喜欢
    • 2016-03-22
    • 1970-01-01
    • 1970-01-01
    • 2012-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多