1. 程式人生 > >javascript實現上傳和下載

javascript實現上傳和下載

使用easyui進行檔案上傳

HTML程式碼

<form id ="uploadform"  style="display:inline-flex;">
                     <input class="easyui-filebox" name="file" id = "file" onfocus=this.blur() data-options="prompt:'Choose a file...'" style="width:100%;">
                     <input name="_tf_token_" type
=
"hidden" value="" id="tr_token"/> <input type="button" value="匯入" onclick="doUpload()" class="button"/> </form>

Javascript程式碼

function doUpload() {
    $('#tr_token').val(tokenValue); // 獲取全域性token值
    var file  = $( "#filebox_file_id_1"
).val(); // filebox_file_id_1 是easyui生成的id // 判斷上傳的檔案格式 var filetype = file.substr(file.length-4,file.length); if(!(filetype.indexOf("csv")>0)){ alertMsg("上傳的檔案格式出錯,請按照模板上傳"); return; } /// 獲取檔案資料 var formData = new FormData($( "#uploadform" )[0]); console.log(formData); $('#dataGrid'
).datagrid("loading"); if(file){ alertMsg("確認匯入檔案?", "", null, function(){ $.ajax({ url: '../AllLimitManageC/addImportRiskBlacklist', type: 'POST', data:formData, dataType : "json", async: false, cache: false, contentType: false, processData: false, success: function (data) { var data = formatJson(globalHtmlCharDecode(data)); if(data.result =="success"){ alertMsg(data.msg); $('#dg').datagrid('loadData',data); $("#dg").datagrid("loaded"); //移除遮蔽 }else{ alertMsg(data.msg, "", null, null); $("#dg").datagrid('loadData', {total:0,rows:[]}); $("#detailPanelIndividual").panel('close'); $("#detailPanelCompany").panel('close'); $("#formWindow").window('close'); } }, error: function (returndata) { alertMsg(data.msg); } }); }); } else { alertMsg("請先選擇檔案", "", null, null); } }

前端頁面展示
這裡寫圖片描述

操作 :
這裡寫圖片描述

下載 :

 // 下載列表
    function downloadTable(tablename){
        var arr =  tablename.split("_");
        var downfilename =  "monthaccount"+"_"+arr[1]+".xls";
        var _url = [];
        var downurl = "../daliyMainc/downloadExcel"
        _url.url = downurl;
        _url.dataType = "json";
        _url.contentType= "application/x-www-form-urlencoded; charset=utf-8";
        _url.type = "post";
        _url.data = {
            "downfilename":downfilename,
        };
        _url.callback = function (data){
            if(data.result == "success"){
              alertMsg("下載成功");
            } else {
                alertMsg(data.msg);
            }
        };
        _url.errorCallback = function(data){
            if(data.readyState == 4 && data.status == 200){
            // 使用post請求最後還會走這個。。。奇怪!
                window.location.href= downurl + "?downfilename="+downfilename;
            }else{
                alertMsg("系統異常");
            }
        };
        getEasyUiJson(_url);
    }