美文网首页
前端通过ajax将文件传给Django后端

前端通过ajax将文件传给Django后端

作者: ___大鱼___ | 来源:发表于2019-05-10 15:44 被阅读0次

    html

    <form action="" id="form_data" method="post" enctype="multipart/form-data" onsubmit="return false">
          
                        <input type="submit" class="btn btn-default" id="export_file" value="导入">
                   
                </form>
    

    js

     $('#export_file').click(function () {
    
                var objFile = document.getElementById("file_");
                if(objFile.value === "") {
                alert("不能空")
                    return;
                 }
    
            $.ajax({
                url: '/test/',
                method: 'POST',
                traditional: true,
                processData: false,
                contentType: false,
                cache: false,
                data: new FormData($('#form_data')[0]),
                success:function (res) {
    
                },
                error: function () {
    
                }
            })
    
    
            })
    

    后端Django处理

    def export_idc_special(request):
        if request.method == 'GET':
            return render(request, 'asset/idc/export_idc_special.html', locals())
        elif request.method == 'POST':
            try:
                print '-------------'
                print request.FILES
                # 获取前端传递过来的数据进行保存
                file_obj = request.FILES.get('file', '')
                file_mame = "Lib/" + str(uuid.uuid1()) + '.xlsx'
                with open(file_mame, 'wb+') as f:
                    for chunk in file_obj.chunks():
                        f.write(chunk)
              
    
            except Exception as e:
                print e
    

    相关文章

      网友评论

          本文标题:前端通过ajax将文件传给Django后端

          本文链接:https://www.haomeiwen.com/subject/pgpaoqtx.html