简体   繁体   English

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

[英]How to send a zip file to frontend to download in DRF

I am trying to send a zip file to frontend so that it could download it in the browser. 我正在尝试将zip文件发送到前端,以便可以在浏览器中下载它。

Zip file has a folders inside and those folders have files: Zip文件中有一个文件夹,而这些文件夹中有文件:

file.zip
    - first folder
      - file1.pdf
      - file2.pdf
    - second folder
      - file3.pdf

I think that I need to convert the file to bytes first to send it as a response so I tried to do this: 我认为我需要先将文件转换为字节以将其作为响应发送,所以我尝试这样做:

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)

It gives the following error while appending to the bytearray: 追加到字节数组时,它会出现以下错误:

an integer is required

the folder was archived like this: 该文件夹的存档方式如下:

zip_file_path = shutil.make_archive(dir_path, 'zip', dir_path)

How can I fix this? 我怎样才能解决这个问题?

OK, it turns out it is a little easier than I thought. 好吧,事实证明这比我想象的要容易一些。 I could easily do this: 我可以轻松做到这一点:

zip_file = open(zip_file_path, 'rb')

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

return response

Appending a byte array is assumed to be executed with an integer that will have the value of the appended byte, since append is mostly comprehended as an operation of adding an item to an array, and bytearray is a numerical sequence. 假定附加字节数组是使用将具有附加字节值的整数执行的,因为大多数append理解为将项目添加到数组的操作,而bytearray是一个数字序列。

For arrays concatenation, just use the + operator, like strings: 对于数组串联,只需使用+运算符即可,例如字符串:

zip_byte_array += byte_content

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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