eliwen

ajax上传文件简单案例

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>

  

发表于 2020-07-10 17:22  立文  阅读(284)  评论(0编辑  收藏  举报
 

分类:

技术点:

相关文章:

  • 2021-11-20
  • 2022-01-01
  • 2021-11-02
  • 2021-08-01
  • 2021-12-07
  • 2021-11-30
猜你喜欢
  • 2022-01-01
  • 2021-12-27
  • 2021-11-16
  • 2021-10-19
  • 2021-10-19
  • 2018-03-14
  • 2021-11-20
相关资源
相似解决方案