今天写代码的时候有个需求,要下载xlsx文件到本地,浏览器直接访问路径不可以,就要单独写个方法,返回包含文件数据的响应头。
from django.http import HttpRequest,FileResponse from django.utils.encoding import escape_uri_path from django.template import RequestContext from codecs import open import os def download(request,kwargs): fileurl = request.GET['fileurl'] filename = os.path.split(fileurl)[1] file = open('kingWeb' +fileurl,'rb') response = FileResponse(file) response['Content-Type'] = 'application/octet-stream' response['Content-Disposition'] = "attachment; filename*=utf-8''{}".format(escape_uri_path(filename)) return response #使用 url/adm/home/download?fileurl=/upload/temp/20180706/201807062313.xlsx #浏览器即可提示下载文件 #escape_uri_path方法是为了将中文文件名转换为url编码 #不然浏览器会读取不到文件名