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如何实现决策树算法

数据描述 每条数据项储存在列表中,最后一列储存结果 多条数据项形成数据集 data=[[d1,d2,d3...dn,result], [d1,d2,d3...dn,resul...

Python实现PS图像调整之对比度调整功能示例

Python实现PS图像调整之对比度调整功能示例

本文实例讲述了Python实现PS图像调整之对比度调整功能。分享给大家供大家参考,具体如下: 这里用 Python 实现 PS 里的图像调整–对比度调整。具体的算法原理如下: (1)、n...

python十进制和二进制的转换方法(含浮点数)

本文介绍了python十进制和二进制的转换方法(含浮点数),分享给大家,也给自己留个笔记,具体如下: 我终于写完了 , 十进制转二进制的小数部分卡了我将近一个小时 上代码 #...

Python使用Tkinter实现转盘抽奖器的步骤详解

Python使用Tkinter实现转盘抽奖器的步骤详解

我使用 Python 中的 Tkinter 模块实现了一个简单的滚动抽奖器,接下来继续写一个简单的转盘抽奖器。 Tkinter 实现滚动抽奖器参考:/post/177913.htm 滚动...

Python之使用adb shell命令启动应用的方法详解

一直有一个心愿希望可以用Python做安卓自动化功能测试,在一步步摸索中,之前是用monkeyrunner,但是发现对于控件ID的使用非常具有局限性,尤其是ID的内容不便于区分 具有重复...