我正在尝试将一个 zip 文件发送到前端,以便它可以在浏览器中下载它。
Zip 文件里面有一个文件夹,这些文件夹有文件:
file.zip
- first folder
- file1.pdf
- file2.pdf
- second folder
- file3.pdf
我认为我需要先将文件转换为字节才能将其作为响应发送,所以我尝试这样做:
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)
附加到字节数组时出现以下错误:
an integer is required
文件夹是这样归档的:
zip_file_path = shutil.make_archive(dir_path, 'zip', dir_path)
我该如何解决这个问题?
最佳答案
好吧,事实证明它比我想象的要容易一些。我可以轻松地做到这一点:
zip_file = open(zip_file_path, 'rb')
response = HttpResponse(zip_file, content_type='application/zip')
response['Content-Disposition'] = 'attachment; filename=name.zip'
return response
关于python - 如何将 zip 文件发送到前端以在 DRF 中下载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41801985/