u_4.html文件
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>Ajax形式的文件上传</title> <!-- 最新版本的 Bootstrap 核心 CSS 文件 --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <script src="/static/js/jquery.js"></script> <script src="/static/js/jquery.cookie.js"></script> <script> $(function () { $('.filebtn').click(function () { var formdata = new FormData(); formdata.append("file_obj", $("#file")[0].files[0]); /* 可以在控制台看下 1.获取Jquery console.log($("#file")); 2.获取input标签 console.log($("#file")[0]); 3.获取input标签files属性 console.log($("#file")[0].files[0]); */ formdata.append("user", $("#user").val()); $.ajax({ url: "/upload/u_44/", type: "post", headers:{ 'X-CSRFTOKEN': $.cookie('csrftoken') }, // Ajax上传文件必备参数 processData: false, // 不处理数据 contentType: false, // 不设置内容类型 data: formdata, success: function (response) { static_dic = JSON.parse(response); if (static_dic['static']){ $('.msg').html('Upload Successful !') } } }); {#点击事件结束#} }) }) </script> </head> <body> <div class="container"> <div class="page-header"> <h1>Ajax形式的文件上传 <small>Subtext for header</small> </h1> </div> <div> 姓名<input type="text" id="user"> 文件<input type="file" name="file_obj" id="file"> <input type="button" class="filebtn" value="提交"> <p class="msg"></p> </div> </div> </body> </html>
view.py文件
from django.shortcuts import render,HttpResponse import json,os from bms import settings # Create your views here. def u_4(request): return render(request,'u_4.html') def u_44(request): static_dic = {'static':True} print(request.POST) print(request.FILES) try: file_obj_name = request.FILES.get('file_obj').name path = os.path.join(settings.BASE_DIR,'upload','media',file_obj_name) with open(path,'wb') as f: for line in request.FILES.get('file_obj'): f.write(line) except Exception as e: static_dic['static']=False return HttpResponse(json.dumps(static_dic))
urls.py文件
from django.urls import path, re_path, include from upload import views urlpatterns = [ re_path('^u_4/$', views.u_4, name='u_4'), re_path('^u_44/$', views.u_44, name='u_44'), ]