Django实现文件上传和下载功能
本文介绍在Django框架下实现文件上传与下载的具体代码。重点对比了HttpResponse与StreamingHttpResponse在处理大文件时的差异,指出后者通过流式传输节省内存但可能影响服务器性能。
本文分享了在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采用流式传输文件内容。根据官方文档的解释:
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在整个响应过程中持续进行文件传输,这可能会降低服务器的性能。
urls.py
url(r'^upload',views.upload),
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持本站。
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













