如何将zip文件发送到前端以在DRF中下载

Jah*_*nov 2 python django zip download django-rest-framework

我正在尝试将zip文件发送到前端,以便可以在浏览器中下载它。

Zip文件中有一个文件夹,而这些文件夹中有文件:

file.zip
    - first folder
      - file1.pdf
      - file2.pdf
    - second folder
      - file3.pdf
Run Code Online (Sandbox Code Playgroud)

我认为我需要先将文件转换为字节以将其作为响应发送,所以我尝试这样做:

zip_file = ZipFile(zip_file_path)

zip_byte_array = bytearray()
for filename in zip_file.namelist():
    byte_content = zip_file.read(filename)
    zip_byte_array.append(byte_content)

return Response(zip_byte_array)
Run Code Online (Sandbox Code Playgroud)

追加到字节数组时,它会出现以下错误:

an integer is required
Run Code Online (Sandbox Code Playgroud)

该文件夹的存档方式如下:

zip_file_path = shutil.make_archive(dir_path, 'zip', dir_path)
Run Code Online (Sandbox Code Playgroud)

我怎样才能解决这个问题?

Jah*_*nov 5

好吧,事实证明这比我想象的要容易一些。我可以轻松做到这一点:

zip_file = open(zip_file_path, 'rb')

response = HttpResponse(zip_file, content_type='application/zip')
response['Content-Disposition'] = 'attachment; filename=name.zip'

return response
Run Code Online (Sandbox Code Playgroud)