Ajax上传文件及携带参数

HTML代码

 <div class="form-group">
        <label class="col-sm-2 control-label">文件上传</label>
        <div class="col-sm-10">
            <input type="file" class="file" id="search_key_file"
                   accept=".csv, application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"/>
        </div>
    </div>
    <div class="form-group">
        <label class="col-sm-2 control-label">渠道来源</label>
        <div class="col-sm-10">
            <input type="radio" name="search_key_type" value="1" checked>
            <label>PC</label>
            <input type="radio" name="search_key_type" value="2">
            <label>移动</label>
        </div>
    </div>
    <div class="form-group">
        <div class="col-sm-10 col-sm-offset-2" style="margin-top: 10px;">
            <button class="btn btn-primary" type="button" onclick="xhrSubmit();">
                确定
            </button>
            <button class="btn btn-white" type="button" onclick="cancelXhrSubmit();">
                返回
            </button>
        </div>
    </div>

JS代码

var file_obj = document.getElementById('search_key_file').files[0];
    console.log(file_obj);
    if (typeof (file_obj) == "undefined") {
        toastr.error("请选择需要导入的搜索词文件");
        return;
    }
    var type = $("input[name='search_key_type']:checked").val();

    var fd = new FormData();
    fd.append('accountId', searchKeyAccountId);
    fd.append('file', file_obj);
    fd.append('type', type);

    $.ajax({
        url: '/**/**',
        type: 'POST',
        data: fd,
        processData: false,  //tell jQuery not to process the data
        contentType: false,  //tell jQuery not to set contentType
        //这儿的三个参数其实就是XMLHttpRequest里面带的信息。
        success: function (result, a1, a2) {
            result = JSON.parse(result);
            if (result.code == 0) {
                toastr.success("导入成功");
                var temp = document.getElementById('search_key_file');
                temp.outerHTML = temp.outerHTML;
                cancelXhrSubmit();
            } else {
                toastr.error(result.msg);
            }
        }
    })

清除上一次选中的文件

 var temp = document.getElementById('search_key_file');
 temp.outerHTML = temp.outerHTML;

猜你喜欢

转载自blog.csdn.net/u010675729/article/details/83269755
今日推荐