urls.py
urlpatterns = [ path(‘admin/‘, admin.site.urls), # ajax 相关
path("ajax_temp/", views.ajax_temp), path("upload/", views.upload), ]
views.py
import os def upload(request): print(request.POST) print(request.FILES) # print(request.body) # 会报错 file_obj = request.FILES.get(‘file_name‘) name = file_obj.name with open(os.path.join("media", name), "wb") as f: for i in file_obj: f.write(i) return HttpResponse(‘上传成功‘)
ajax_temp.html
<h3>form表单上传文件</h3> <form action="/upload/" method="POST" enctype="multipart/form-data"> {% csrf_token %} <input type="text" id="user" name="user"> <input type="file" id="file1" name="file_name"> <button id="btn5">ajax上传文件</button> <input type="submit"> </form> <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script> <script> {#ajax上传文件#} $("#btn5").click(function () { var formdata = new FormData(); formdata.append("csrfmiddlewaretoken", $("[name=‘csrfmiddlewaretoken‘]").val()); formdata.append("file_name", $("#file1")[0].files[0]); $.ajax({ url: "/upload/", type: "post", processData: false, // 告诉jQuery不要去处理发送的数据 contentType: false, // 告诉jQuery不要去设置Content-Type请求头 data: formdata, success: function (data) { console.log(data); } }) }) </script>