1. 程式人生 > 其它 >django 實現檔案上傳功能

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

在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>