kongbailongtian 2023-03-17 14:58 采纳率: 0%
浏览 38
已结题

使用Django进行下载zip出现乱码

使用Django进行下载zip出现乱码
1 将文件进行压缩成zip


```python
def zip_dir(folder_path, images_path, vis_path, fig_path, chinese_path, english_path):
    name = str(time.time())
    folder_name = os.path.join(folder_path, "{0}.zip".format(name))
    file_list = []
    for i in range(len(images_path)):
        file_list.append(images_path[i])
        file_list.append(vis_path[i])
        file_list.append(fig_path[i])
        file_list.append(chinese_path[i])
        file_list.append(english_path[i])
    zf = zipfile.ZipFile(folder_name, "w", zipfile.zlib.DEFLATED)
    for tar in file_list:
        arc_name = tar[len(folder_path):]
        zf.write(tar, arc_name)
    zf.close()
    return folder_name, name

2 传输zip
def file_iterator(filename, chunk_size=512):
    with open(filename, 'rb') as f:
        while True:
            c = f.read(chunk_size)
            if c:
                yield c
            else:
                break
def download_sub(request):
    // 省略获得文件路径images_root, images_path, vis_path, fig_path, chinese_path, english_path等代码
    folder_name, name = zip_dir(images_root, images_path, vis_path, fig_path, chinese_path, english_path)
    response = StreamingHttpResponse(file_iterator(folder_name))
    response['Content-Type'] = 'application/octet-stream'
    response['Content-Disposition'] = 'attachment;filename="{0}.zip"'.format(name)
    return response

3 网页响应

img

img

img

  • 写回答

3条回答 默认 最新

  • 追cium 2023-03-17 15:05
    关注

    参考GPT和自己的思路:

    根据您提供的代码和截图,可以看出出现乱码的问题可能是因为您在下载时没有设置文件编码方式,可以尝试在响应头部增加一个charset字段来设置编码方式。

    具体的修改方法如下:

    response = StreamingHttpResponse(file_iterator(folder_name))
    response['Content-Type'] = 'application/zip'
    response['Content-Disposition'] = 'attachment;filename="{0}.zip"'.format(name)
    response['charset'] = 'UTF-8'   # 增加charset字段,设置编码方式
    return response
    

    另外,建议在文件传输的过程中使用二进制模式,可以通过在open函数中设置参数"rb"来实现。

    希望以上回答能够帮到您解决问题,如有疑问或者问题还未解决,请随时联系我。

    评论

报告相同问题?

问题事件

  • 已结题 (查看结题原因) 3月21日
  • 修改了问题 3月17日
  • 创建了问题 3月17日

悬赏问题

  • ¥100 复现论文:matlab仿真代码编写
  • ¥15 esp32驱动GC9A01循环播放视频
  • ¥15 惠普360g9的最新bios
  • ¥30 这个功能用什么软件发合适?
  • ¥60 微信小程序,取消订单,偶尔订单没有改变状态
  • ¥15 用pytorch实现PPO算法
  • ¥15 关于调制信号的星座图?
  • ¥30 前端传参时,后端接收不到参数
  • ¥15 这是有什么问题吗,我检查许可证了但是显示有呢
  • ¥15 机器学习预测遇到的目标函数问题