Django实现文件上传和下载功能

yipeiwu_com5年前Python基础

本文实例为大家分享了Django下完成文件上传和下载功能的具体代码,供大家参考,具体内容如下

一、文件上传

Views.py

def upload(request):
 if request.method == "POST": # 请求方法为POST时,进行处理
 myFile = request.FILES.get("myfile", None) # 获取上传的文件,如果没有文件,则默认为None
 if not myFile:
 return HttpResponse("no files for upload!")
 # destination=open(os.path.join('upload',myFile.name),'wb+')
 destination = open(
 os.path.join("你的文件存放地址", myFile.name),
 'wb+') # 打开特定的文件进行二进制的写操作
 for chunk in myFile.chunks(): # 分块写入文件
 destination.write(chunk)
 destination.close()
 return HttpResponse("upload over!")
 else:
 file_list = []
 files = os.listdir('D:\python\Salary management system\django\managementsystem\\file')
 for i in files:
 file_list.append(i)
 return render(request, 'upload.html', {'file_list': file_list})

urls.py

url(r'download/$',views.download),

upload.html

<div class="container-fluid">
 <div class="row">
 <form enctype="multipart/form-data" action="/upload_file/" method="POST">
 <input type="file" name="myfile"/>
 <br/>
 <input type="submit" value="upload"/>
 </form>
 </div>
</div>

 页面显示

 

二、文件下载

Views.py

from django.http import HttpResponse,StreamingHttpResponse
from django.conf import settings
 
def download(request):
 filename = request.GET.get('file')
 filepath = os.path.join(settings.MEDIA_ROOT, filename)
 fp = open(filepath, 'rb')
 response = StreamingHttpResponse(fp)
 # response = FileResponse(fp)
 response['Content-Type'] = 'application/octet-stream'
 response['Content-Disposition'] = 'attachment;filename="%s"' % filename
 return response
 fp.close()

HttpResponse会直接使用迭代器对象,将迭代器对象的内容存储城字符串,然后返回给客户端,同时释放内存。可以当文件变大看出这是一个非常耗费时间和内存的过程。

而StreamingHttpResponse是将文件内容进行流式传输,StreamingHttpResponse在官方文档的解释是:

The StreamingHttpResponse class is used to stream a response from Django to the browser. You might want to do this if generating the response takes too long or uses too much memory.

这是一种非常省时省内存的方法。但是因为StreamingHttpResponse的文件传输过程持续在整个response的过程中,所以这有可能会降低服务器的性能。

urls.py

url(r'^upload',views.upload),

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python lxml解析HTML并用xpath获取元素的方法

代码 使用方法见注释 #-*- coding: UTF-8 -*- from lxml import etree source = u''' <div><p c...

Python搭建APNS苹果推送通知推送服务的相关模块使用指南

APNS 是苹果为IOS设备提供的推送服务,全称是(Apple Push Notification service)。 如果你有接触移动互联网相关的开发的话,应该对它很熟悉。 接下来我会...

详解Django中Request对象的相关用法

详解Django中Request对象的相关用法

从Request对象中获取数据 我们在第三章讲述View的函数时已经介绍过HttpRequest对象了,但当时并没有讲太多。 让我们回忆下:每个view函数的第一个参数是一个HttpRe...

详解numpy.meshgrid()方法使用

详解numpy.meshgrid()方法使用

一句话解释numpy.meshgrid()——生成网格点坐标矩阵。 关键词:网格点,坐标矩阵 网格点是什么?坐标矩阵又是什么鬼? 看个图就明白了: 图中,每个交叉点都是网格点,描...

详解重置Django migration的常见方式

根据django官方文档建议,开发过程中会把生成的migrations提交到git中。由于各种原因,会有一些场景需要重置migrations,故总结一些常用场景及解决办法。 场景一 不...