这里只列出关键部分

urls.py

urlpatterns = [
    # 其他
    path('file_put/', views.file_put),
]

views.py

def file_put(request):
    if request.method == "POST":
        #print("body-->", request.body)
        print("POST-->", request.POST)
        print(request.POST.get("user"))
        print(request.FILES)
        # dowload file code
        file_obj = request.FILES.get("avatar")
        with open(file_obj.name, "wb") as f:
            for line in file_obj:
                f.write(line)
        return HttpResponse("OK")

    return render(request, "upload.html")

upload.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h3>基于Ajax的文件上传</h3>

<form action="" method="post" enctype="multipart/form-data">
     用户名 <input type="text" >
     头像 <input type="file" >
     <input type="button" class="btn" value="Ajax">
</form>

<script src="/static/jquery-3.3.1.min.js"></script>
<script>
     $(".btn").click(function () {
         var formdata = new FormData();
         formdata.append("user", $("#user").val());
         formdata.append("avatar", $("#avatar")[0].files[0]);
         $.ajax({
             url:"/file_put/",
             type:"post",
             contentType:false,
             processData:false,
             data:formdata,
             success:function (data) {
                 console.log(data);
             }
         });
     });
</script>
</body>
</html>

Django ajax 上传文件
Django ajax 上传文件

相关文章:

  • 2022-02-07
  • 2022-12-23
  • 2022-12-23
  • 2021-06-21
  • 2022-01-29
  • 2021-11-20
  • 2021-11-20
  • 2022-01-01
猜你喜欢
  • 2021-12-17
  • 2021-12-03
  • 2022-12-23
  • 2021-08-25
  • 2021-08-14
相关资源
相似解决方案