1. {% load static %}
    2. <!DOCTYPE html>
    3. <html lang="en">
    4. <head>
    5. <meta charset="UTF-8">
    6. <title>网页上传</title>
    7. </head>
    8. <body>
    9. <h1> 欢迎使用网页上传文件 </h1>
    10. <form>
    11. {% csrf_token %}
    12. 用户名: <input type="text" name="user">
    13. 头像: <input type="file" name="head-png" id="file" multiple>
    14. <input type="button" id="ajax-submit" value="提交">
    15. <span style="color:#00ff04;font-size: 12px;" id="info"></span>
    16. </form>
    17. <script src="{% static 'jquery.js' %} "></script>
    18. <script>
    19. $("#ajax-submit").click(function () {
    20. var formdata=new FormData(); // ajax上传文件的时候,需要这个类型,它会将添加给它的键值对加工成formdata的类型
    21. formdata.append("user",$("#user").val()); // 添加键值的方法是append,注意写法,键和值之间是逗号
    22. formdata.append("csrfmiddlewaretoken",$("[name='csrfmiddlewaretoken']").val());
    23. formdata.append("head-png",$("#file")[0].files[0]);
    24. $.ajax({
    25. url:"/app01/index/",
    26. type:"post",
    27. data:formdata,
    28. processData: false , // 不处理数据
    29. contentType: false, // 不设置内容类型
    30. success:function (data) {
    31. console.log(data)
    32. var resStr = JSON.parse(data)
    33. if (resStr['code'] === "0000"){
    34. var spanEle = document.createElement('span');
    35. $('#info').text(resStr['msg']);
    36. }
    37. }
    38. })
    39. })
    40. </script>
    41. </body>
    42. </html>

    views.py

    1. import os.path
    2. from django.shortcuts import render,HttpResponse,redirect
    3. from django.views import View
    4. from django.conf import settings
    5. # Create your views here.
    6. class index(View):
    7. html = 'h5_upload_file.html'
    8. def get(self,request):
    9. # print(request.GET) # <QueryDict: {}> GET请求数据
    10. return render(request,self.html)
    11. def post(self,request):
    12. user = request.POST.get('user')
    13. file_obj = request.FILES.get('head-png')
    14. file_name = os.path.join(settings.BASE_DIR,'img',file_obj.name) # project/img/filename
    15. with open(file_name,'wb') as f:
    16. for i in file_obj:
    17. f.write(i)
    18. res = '{"code":"0000","msg":"%s upload success!","url":"/app01/msg/"}' % file_obj.name
    19. return HttpResponse(res)

    image.png