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

本文实例为大家分享了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("你的文件存放地址",'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>

页面显示

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

二、文件下载

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),

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

相关文章

在这篇文章中,我们深入学习了XPath作为一种常见的网络爬虫技巧。XPath是一种用于定位和选择XML文档中特...
祝福大家龙年快乐!愿你们的生活像龙一样充满力量和勇气,愿你们在新的一年里,追逐梦想,勇往直前,不...
今天在爬虫实战中,除了正常爬取网页数据外,我们还添加了一个下载功能,主要任务是爬取小说并将其下载...
完美收官,本文是爬虫实战的最后一章了,所以尽管本文着重呈现爬虫实战,但其中有一大部分内容专注于数...
JSON是一种流行的数据传输格式,Python中有多种处理JSON的方式。官方的json库是最常用的,它提供了简单...
独立样本T检验适用于比较两组独立样本的均值差异,而配对T检验则适用于比较同一组样本在不同条件下的均...