最近一个用django开发的web项目要进行数据的导入导出,所以有必要了解下。
django中主要用HttpResponse将请求结果返回给浏览器,所以文件的下载也是通过改对象进行处理的,具体的一个列子的代码如下:
[python] view plain copy
#文件下载 def download(request):
"""
Send a file through Django without loading the whole file into
memory at once. The FileWrapper will turn the file object into an
iterator for chunks of 8KB.
"""#读取mongodb的文件到临时文件中
fileid_=request.GET["fileid"]
filepath_ = ('%s/%s'%(MEDIA_ROOT, fileid_)) #文件全路径
file_=TFiles.objects.get(fileid=int(fileid_))
filename_=file_.filename
filetype_=file_.filetype
if os.path.isfile(filepath_):
passelse:
mongoLoad(fileid_)
#下载文件 def readFile(fn, buf_size=262144):#大文件下载,设定缓存大小
f = open(fn, "rb")
while True:#循环读取
c = f.read(buf_size)
if c:
yield c
else:
break
f.close()
response = HttpResponse(readFile(filepath_), content_type='APPLICATION/OCTET-STREAM') #设定文件头,这种设定可以让任意文件都能正确下载,而且已知文本文件不是本地打开
response['Content-Disposition'] = 'attachment; filename='+filename_.encode('utf-8') + filetype_.encode('utf-8')#设定传输给客户端的文件名称
response['Content-Length'] = os.path.getsize(filepath_)#传输给客户端的文件大小 return response