1. 程式人生 > >Ajax上傳檔案及攜帶引數

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;