Django中下载的文件损坏

0 投票
1 回答
552 浏览
提问于 2025-04-17 23:49

我在views.py文件里写了这个函数:

def download(request):

    file = open("D:\wamp\www\User_App.rar","r")
    mimetype = mimetypes.guess_type("D:\wamp\www\User_App.rar")[0]
    if not mimetype: mimetype = "application/octet-stream"

    response = HttpResponse(file.read(), mimetype=mimetype)
    response["Content-Disposition"]= "attachment; filename=%s" % os.path.split("D:\wamp\www\User_App.rar")[1]
    return response

这个函数是用来下载文件的,但下载后打开文件时发现它损坏了。请问怎么解决这个问题呢?

1 个回答

3

以二进制模式打开文件:

file = open(r"D:\wamp\www\User_App.rar", "rb")

因为以文本模式打开文件时,换行符会被转换成一个平台通用的 \n 字符。

撰写回答