按鈕和輸入框關聯;文件上傳解決二次不觸發change事件

html代碼:

<div class="text-center">
    <input type="file" class="input-file" id="importExcel">
    <button class="btn btn-info input-file-btn">導入EXCEL表格</button>
    <button class="btn btn-info" onclick="calculate()">計算</button>
</div>

js代碼:

// 按鈕和輸入框關聯
$(".input-file-btn").on("click", function () {
    $(".input-file").trigger("click");
});
// 導入Excel表格
$("#importExcel").on("change", function () {
    // js 獲取文件對象
    console.log($(this)); // n.fn.init [input#importExcel.input-file, context: input#importExcel.input-file]
    console.log($(this).get(0)); // <input type="file" class="input-file" id="importExcel">
    console.log($(this).get(0).files); // FileList {0: File, length: 1}
    var fileObj = $(this).get(0).files[0]; //
    /* File {name: "配件計算(3).xlsx", lastModified: 1551083247769, lastModifiedDate: Mon Feb 25 2019 16:27:27 GMT+0800 (中國標準時間), webkitRelativePath: "", size: 9788, …}
	lastModified: 1551083247769
	lastModifiedDate: Mon Feb 25 2019 16:27:27 GMT+0800 (中國標準時間) {}
	name: "配件計算(3).xlsx"
	size: 9788
	type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
	webkitRelativePath: ""
	__proto__: File
*/
    // 新建要傳遞的參數對象
    var formFile = new FormData();
    // 加入文件對象
    formFile.append("file", fileObj);
    var checkLindex;
    $.ajax({
        //請求路徑
        "url": reqUrl + "/partsCalaulate/upload",
        "data": formFile,
        // 請求類型
        "type": "Post",
        "dataType": "json",
        //上傳文件無需緩存
        "cache": false,
        //用於對data參數進行序列化處理 這裏必須false
        "processData": false,
        //必須
        "contentType": false,
        "beforeSend": function () {
            // 彈出loading
            checkLindex = layer.load();
        },
        "success": function (data) {
            $("#importExcel").val(''); //及時清空避免二次選擇同一文件時:1.不能觸發change事件;2.點擊取消時沒有發起請求
            ...
        },
        error: function (data) {
            //關閉loading
            layer.close(checkLindex);
            //彈出提示
            layer.msg("服務連接異常", {time: 1100, icon: 7});
        }
    })
});
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章