首先上结构
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路径,并且显示上传文件成功