Ajax之文件上传处理

来源:互联网 发布:羽绒被品牌评测知乎 编辑:程序博客网 时间:2024/06/05 21:05

前台处理

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Title</title>    <script src="/static/jquery3.2.1.js"></script>    <script src="/static/dist/sweetalert2.all.min.js"></script>    <link rel="stylesheet" href="/static/dist/sweetalert2.min.css">    <script src="https://cdn.bootcss.com/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>    <script>        $(function () {            var formData = new FormData();            formData.append('file', $('#file')[0].files[0]);            $('#sbt').click(function () {                $.get({                    url: '/get_result/',                    data: formData,                    done: function (data) {                        alert('hello,jj')                    },                    fail: function () {                        alert('失败')                    }                })            })        })    </script></head><body><form action="/get_result/" method="post" enctype="multipart/form-data">    {% csrf_token %}    <p>文件<input type="file" name="file" id="file"></p>    <input type="submit" value="提交" id="sbt"></form></body></html>

后台处理

def get_result(request):    with open(request.FILES.get('file').name, 'wb') as f:        for item in request.FILES.get('file'):            f.write(item)    return HttpResponse('OK')

关键点在于:

前台通过$('#file')[0].files[0]获取上传的文件对象,后台通过request.Files.get('file')获取文件对象。
原创粉丝点击