目录
1.创建Django项目
Django之创建项目【二】:https://blog.csdn.net/Burgess_zheng/article/details/86505526
2.创建app(并且app目录下创建一个urls.py文件)
进入项目目录下
创建app命令:
F:\Burgess\Python\pycharm实验脚本\test\project_burgess>python manage.py startapp submit_views
3.定义setting配置文件的静态目录路径和创建静态目录(我们需要js文件)
路径:project_burgess/project_burgess/setting
4.定义请求的URL路由分发
路径:project_burgess/project_burgess/urls.py
from django.contrib import admin from django.urls import path,re_path #Django版本2.0以上 from project_burgess import views from django.conf.urls import url #Django2.0 from django.conf.urls import include urlpatterns = [ path('admin/', admin.site.urls), #提交各种数据数据类型测试 re_path('submit/', include("submit_views.urls")), # url(r'^submit/', include("submit_views.urls")), ]
5.定义app下的URL路由
路径:project_burgess/submit_views/urls.py
__author__ = "Burgess Zheng" #!/usr/bin/env python #-*- coding:utf-8 -*- from django.urls import path,re_path #Django版本2.0以上 from submit_views import views from django.conf.urls import url #Django2.0 app_name='namespace' urlpatterns = [ #upload_file re_path('upload/', views.upload), ]
6.定义url对应函数处理
路径:project_burgess/submit_views/views.py
def upload(request): if request.method == "GET": return render(request, 'upload.html') elif request.method == "POST": username = request.POST.get('username') file_obj = request.FILES.get('fafafa') import os img_path = os.path.join('static/imgs/',file_obj.name) #手动在static下创建一个imags目录 #其实这里我们可以进行判断该imgs目录是否存在,不存在就创建 with open(img_path,'wb') as f: #文件保存到指定路径 for item in file_obj.chunks(): f.write(item) ret = {'code': True , 'data': img_path} #文件路径返回给前端 import json return HttpResponse(json.dumps(ret))
7.定义响应的html文件
对ajax(jQuery,原生XMLhttpRequest)、iframe、CSRF不熟悉请先跳转到如下文章:
Django之Ajax(jQuery)and原生Ajax(XMLhttpRequest))【交互篇五】 https://blog.csdn.net/Burgess_zheng/article/details/86548396
实战Django之Ajax(jQuery)前后端交互 https://blog.csdn.net/Burgess_zheng/article/details/86548407
实战Django之iframe介绍和交互 https://blog.csdn.net/Burgess_zheng/article/details/86558181
Django之CSRF XSS原理解析【交互篇四】https://blog.csdn.net/Burgess_zheng/article/details/86548425
路径:project_burgess/templates/upload.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> <style> .upload{ display: inline-block;padding: 10px; background-color: brown; position: absolute; top: 0; bottom: 0; right: 0; left: 0; z-index: 90; } .file{ width: 100px;height: 50px;opacity: 0; position: absolute; top: 0; bottom: 0; right: 0; left: 0; z-index: 100; } </style> </head> <body> <a id="csrf" style="display: none">{{ csrf_token }}</a> <div style="position: relative;width: 100px;height: 50px;"> <input class="file" type="file" id="fafafa" name="afafaf" /> <a class="upload">上传</a> </div> <input type="button" value="提交XHR" onclick="xhrSubmit()" /> <input type="button" value="提交jQuery" onclick="jqSubmit()" /> <hr/> <form id="form1" action="/submit/upload/" method="POST" enctype="multipart/form-data" target="ifm1"> {% csrf_token %} <iframe id="ifm1" name="ifm1" style="display: none;"></iframe> <input type="file" name="fafafa" onchange="changeUpalod();" /> <!--检测到有文件上传就触发指定函数,所以我们就无需弄个提交标签--> <!--<input type="submit" onclick="iframeSubmit();" value="Form提交"/>--> </form> <div id="preview"></div> <script type="text/javascript" src="/static/jquery-1.12.4.js"></script> <script> function changeUpalod(){ //检测到有上传文件触发该函数 //匹配的iframe绑定一个load事件 //当接收到后台响应信息的时候会触发该事件函数 //下面这种绑定形式和 <iframe id="ifm1" name="ifm1" onload='func()'></iframe>一样的 $('#ifm1').load(function(){ var text = $('#ifm1').contents().find('body').text(); //获取ifml嵌套html里面的body下的内容(后端的响应信息) var obj = JSON.parse(text); //反序列化响应数据 $('#preview').empty(); //清空匹配标签下的所有标签 var imgTag = document.createElement('img'); //创建一个img标签 imgTag.src = "/" + obj.data; //obj.data:后端返回文件或图片的路径进行拼接 //添加img标签的src内部属性值 //实现图片预览功能 $('#preview').append(imgTag); //追加到指定标签的下 }); $('#form1').submit(); } function jqSubmit(){ // $('#fafafa')[0] console.log(1111111111111); var file_obj = document.getElementById('fafafa').files[0]; var fd = new FormData();//相当一个form表单(和字典一样) fd.append('username','root');//追加key和value,value可为字符串也可以是对象 fd.append('fafafa',file_obj); $.ajax({ url: '/submit/upload/', type: 'POST', data: fd, headers:{'X-CSRFtoken':$('#csrf').text()}, processData: false, // tell jQuery not to process the data contentType: false, // tell jQuery not to set contentType success:function(arg,a1,a2){ console.log(arg); console.log(a1); console.log(a2); } }) } function xhrSubmit(){ // $('#fafafa')[0] //获取dom对象 console.log(1111111111111); var file_obj = document.getElementById('fafafa').files[0]; //匹配上传文件标签.files[0]:已上传文件对象 var fd = new FormData(); //相当一个form表单(和字典一样) fd.append('username','root'); //追加key和value,value可为字符串也可以是对象 fd.append('fafafa',file_obj); var xhr = new XMLHttpRequest(); //创建一个XMLHttpRequest对象 xhr.open('POST', '/submit/upload/',true); //创建请求 xhr.onreadystatechange = function(){ //当readyState的值改变时自动触发执行其对应的函数(回调函数) if(xhr.readyState == 4){ /* Number readyState 状态值(整数) 详细: 0-未初始化,尚未调用open()方法; 1-启动,调用了open()方法,未调用send()方法; 2-发送,已经调用了send()方法,未接收到响应; 3-接收,已经接收到部分响应数据; 4-完成,已经接收到全部响应数据; */ // 接收完毕 var obj = JSON.parse(xhr.responseText);//反序列化响应数据 console.log(obj); } }; xhr.setRequestHeader('X-CSRFtoken',$('#csrf').text()); //添加头部信息 xhr.send(fd);//发送请求 } </script> </body> </html>
8.启动Django
手动:python manage.py runserver 127.0.0.1:8000
pycharm:
9.浏览器访问URL结果
GET请求
原生ajax(XMLHttpRequest()对象方式):点击上传随便上传个文件图片,然后点击-->提交XHR
jquery ajax方式:点击上传随便上传个文件图片,然后点击-->提交jQuery
iframe方式:点击选择文件,随便上传个图片,做了预览功能(上面ajax接收了后端提交的图片路径也可做预览)
查看后端保存文件的目录
主篇:Django之ajax文件上传的两种方式和ifname上传文件【交互篇六】 https://blog.csdn.net/Burgess_zheng/article/details/86558155