首先上結構 mynode -> app5 -> urls.py & views.py | -> templates -> 5 -> upload.html | -> mynode -> urls.py | -> media 按照順序,先上app5/urls.py from django.urls i ...
首先上結構
mynode -> app5 -> urls.py & views.py
| -> templates -> 5 -> upload.html
| -> mynode -> urls.py
| -> media
按照順序,先上app5/urls.py
from django.urls import path
from app5 import views as v5
app_name = 'app5'
urlpatterns = [
path('upload_file/', v5.upload_file, name = 'upload_file'),
path('show_upload/', v5.show_upload, name = 'show_upload'),
]
path('upload_file/', v5.upload_file, name = 'upload_file'),指定upload_file跳轉功能
path('show_upload/', v5.show_upload, name = 'show_upload'),指定show_upload跳轉功能
接著是app5/view.py
from django.shortcuts import render
from django.http import HttpResponse import os def show_upload(request): return render(request, '5/upload.html') def upload_file(request):if request.method == 'POST': get_file = request.FILES.get('myfile',None) if get_file: path = 'media/uploads' if not os.path.exists(path): os.makedirs(path) dest = open(os.path.join(path,get_file.name),'wb+') for chunk in get_file: dest.write(chunk) dest.close() return HttpResponse('上傳文件成功!') else: return HttpResponse('沒有上傳文件!')
首先寫了一個show_upload方法,跳轉到初始頁面
接下來是upload_file方法,首先判斷請求方式是否是POST,接下來獲取上傳文件,指定上傳路徑,如果路徑不存在就創建一個,把上傳文件內容寫到指定路徑下
再來是templates/5/upload.html
<!--<from enctype="multipart/form-data" action="{% url 'app5:upload_file' %}" method="post">--> //這個是錯誤的
<form enctype="multipart/form-data" action="{% url 'app5:upload_file' %}" method="post"> {% csrf_token %} <input type="file" name="myfile" /> <br/> <input type="submit" value="upload_file" /> </form>
<!--</from>--> //這個是錯誤的
指定了一個action,{% url 'app5:upload_file' %},app5是app5/urls.py中的app_name,upload_file則是要跳轉連接,同時因為url已經指定這個連接要跳轉的views中的功能,因此這個就是app5/view.py裡面的upload_file方法
這個頁面展示是正常的,但是在寫好功能以後,無論怎麼點提交,都沒法跳轉到upload_file功能
仔細看表單的名稱<from,這個坑我踩了好久,後來仔細看了下,應該是form,改了之後就好使了
最後是mynode/urls.py
from django.contrib import adminfrom django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('app5/', include('app5.urls')), ]
指定app5跳轉到app5/urls.py
最後打開瀏覽器,輸入鏈接http://localhost:8000/app5/show_upload/
選擇要上傳的文件,點擊upload_file按鈕
這裡跳轉到upload_file路徑,並且顯示上傳文件成功