django 实现文件上传功能

 文件上传原理是无论上传的文件格式是什么,将文件以二进制的数据格式读取并写入网站指定的文件里。

在myApp下配置urls.py路由:

#myApp urls.py

from argparse import Namespace
from operator import index
from django.urls import path,re_path,include
from . import views
from django.views.generic import RedirectView

urlpatterns = [
    path("",views.index,name="index"),
    path("download/file1",views.download1,name="download1"),
    path("download/file2",views.download2,name="download2"),
    path("download/file3",views.download3,name="download3"),
    path("upload",views.upload,name="uploaded")

]

#配置全局404页面
handler404 = "myApp.views.page_not_found"

#配置全局500页面
handler500 = "myApp.views.page_error"

在myApp应用的视图中,实现文件上传的功能:

from django.shortcuts import render
from django.http import HttpResponse

import os

# Create your views here.

def index(request):
    # return redirect("index:shop",permanent=True)
    return render(request,"index.html")

def upload(request):
    #请求方法为POST时,执行文件上传
    print("debug ++++++++++++++++++++++++")
    print(request.method)
    if request.method == "POST":
        #获取上传的文件,如果没有文件,就默认为None
        myFile = request.FILES.get("myfile",None)
        if not myFile:
            return HttpResponse("no files for upload")
        #打开特定的文件进行二进制的写操作
        f = open(os.path.join("E:\myDjango\\file",myFile.name),"wb+")
        #分块写入文件
        for chunk in myFile.chunks():
            f.write(chunk)
        f.close()
        return HttpResponse("upload over!")
    else:
        #请求方法为get时,生成文件上传页面
        return render(request,"index.html")
  • 浏览器将用户上传的文件读取后,通过http的post请求将二进制数据传到django,当django收到post请求后,从请求对象的属性FILES获取文件信息,然后再D盘的upload文件夹里创建新的文件,文件名(从文件信息对象myFile.name属性获取),与用户上传的文件名相同。
  • 从文件信息对象myFile.chunks()读取文件内容,并写入D盘的upload文件夹的文件中。
  • myFile.name 获取上传文件的文件名,包含文件后缀名。
  • myFile.size 获取上传文件的文件大小。
  • myFile.content_type 获取文件类型,通过后缀名判断文件类型。
  • myFile.read() 从文件对象里读取整个文件上传的数据,这个方法只适合小文件。
  • myFile.chunks() 按流式响应方式读取文件,在for循环中进行迭代,将大文件分块写入服务器所指定的保存位置。
  • myFile.multiple_chunks() 判断文件对象的文件大小,返回True或者False,当文件大于2.5MB时,该方法返回True,否则返回False,因此,可以根据该方法来选择选用read()方法读取还是采用chunks()方法读取

在index.html中,添加上传文件的控件:

<html>
    <header>
        <title>首页文件处理</title>
    </header>

<body>
        <a href="{%url 'myApp:download1' %}">下载1</a>
        <a href="{%url 'myApp:download2' %}">下载2</a>
        <a href="{%url 'myApp:download3' %}">下载3</a>

        <form enctype="multipart/form-data" action="/upload" method="post">
            <!-- django 的csrf 防御机制 -->
            {%csrf_token%}
            <input type="file" name="myfile" />
            <br>
            <input type="submit" value="上传文件" />
        </form>


</body>

</html>

在模板文件index.html使用form标签的文件控件file生成文件上传功能,该控件将用户上传的文件以二进制的形式读取,读取方式由form标签的属性entype=“multipart/form-data”设置

 

posted @ 2022-04-10 10:37  西夏一品唐  阅读(1611)  评论(0编辑  收藏  举报