猿问

Django如何在内存里处理ajax传递进来的Excel文件?

希望通过ajax从页面上传一些字段和一个excel文件进行处理


前端部分是这样写的


<form method="post">

    {% csrf_token %}

    <input class='a' type="text">

    <input class="up-files" type="file">

    <button class="up-btn">提交</button>

</form>


#js 部分

<script>

$('.wage-add-btn').click(function () {

         $.ajaxSetup({

     data: {csrfmiddlewaretoken: '{{ csrf_token }}' },

    });

         if(confirm("请仔细检查表格确认上传")) {

             var a = $('.a').val();

             var files = $('.up-files').val();

             $.ajax({

                type:"POST",

                data: {a:a, files:files},

                url: "{% url 'add' %}",

                cache: false,

                dataType: "html",

                success: function(){

                    alert('成功')

                },

                error: function(){

                    alert('失败')

                }

            });

            return false;

         }

    });


</script>


views.py:


def add(request):


if request.method == 'POST':

    if request.is_ajax():

        a = request.POST.get('a')

        files = request.POST.get('files')

        data = xlrd.open_workbook(files)

return render(request, 'index.html', locals())

这里报错:

IOError: [Errno 2] No such file or directory: u'C:\fakepath\u5956u54c1u53d1u653eu767bu8bb0u886835.xls'


请问是哪里操作不对吗?是否有完整的实现可以借鉴?


大话西游666
浏览 924回答 3
3回答

德玛西亚99

文件是通过request.FILE传输,不是通过POST

倚天杖

前端的ajax写的不对,file的上传要借助formData,<form method="post">{% csrf_token %}<input class='a' type="text"><input class="up-files" type="file"><button class="up-btn">提交</button></form>js 部分<script>$('.wage-add-btn').click(function () {&nbsp; &nbsp; &nbsp;$.ajaxSetup({&nbsp;data: {csrfmiddlewaretoken: '{{ csrf_token }}' },});&nbsp; &nbsp; &nbsp;if(confirm("请仔细检查表格确认上传")) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// var a = $('.a').val();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// var files = $('.up-files').val();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;var form = new FormData();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;form.append("file", files);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;form.append("a", a);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;$.ajax({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; type:"POST",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; data: form,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; url: "{% url 'add' %}",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; cache: false,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; dataType: "html",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; success: function(){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; alert('成功')&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; error: function(){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; alert('失败')&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; &nbsp;}});</script>
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答