django中的Ajax文件上传

主要介绍两个

1.ajax文件上传

2.写路由器

3.创建对应的函数

4.file_put.html代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

</head>
<body>

<h3>Ajax文件的上传</h3>
<div>
    {% csrf_token %}
    姓名<input type="text" id="user">
    文件<input type="file" name="file_obj" id="file">
    <input type="button" class="filebtn" value="提交">
    <p class="msg"></p>
</div>
<script src="/static/jquery.js"></script>
<script>
    $(".filebtn").click(function () {

          var formdata=new FormData();
          formdata.append("file_obj",$("#file")[0].files[0]);
          formdata.append("user",$("#user").val());

          $.ajax({
              url: "/file_put/",
              type: "post",

              // Ajax上传文件必备参数
              processData: false,    // 不处理数据
              contentType: false,    // 不设置内容类型

              data: formdata,
              success: function (response) {
                  console.log(response);
                  if (response == "OK") {
                      $(".msg").html("提交成功!")
                  }
              }
          })

      })

</script>
</body>
</html>

5.上传成功之后我们得下载下来

# 本地下载函数
def file_put(request):

    print(request.POST)
    print(request.FILES)
    file_obj=request.FILES.get("file_obj")
    print(file_obj)
    # 文件对象有一个name属性,获取文件名称字符串
    print(file_obj.name)
    path = file_obj.name

    path = os.path.join(settings.BASE_DIR,"media","img",path)   #进行下载文件保存的地址拼接,注意的是,当前项目里没有
media文件和它下面的img文件,需要我们手动的去创建
with open(path,"wb") as f: for line in file_obj: f.write(line) return HttpResponse("OK")

成功之后,在你当前的项目里就会有这个文件夹和你下载之后的文件

原文地址:https://www.cnblogs.com/lzqrkn/p/9880299.html