天天看點

Ajax下載下傳檔案(頁面無重新整理)

說明:Ajax是無法實作檔案傳輸的,本文隻是模拟了Ajax不重新整理頁面就可以請求并傳回資料的效果。實質上還是通過送出form表單來傳回檔案流的輸出。

分步實作邏輯:

  1. ajax請求伺服器,通路資料庫,根據查詢到的資料生成一個資料檔案,傳回前台一個json對象(可放置生成成功标記,檔案路徑等資訊)。
  2. ajax success回調函數部分,根據傳回的json對象,調用手寫的js下載下傳檔案的方法,實作頁面無重新整理下載下傳檔案。

貼上部分代碼供參考:

js代碼:

1. js寫一個動态建立并送出form表單的方法,依賴于jQuery插件。

// 檔案下載下傳
jQuery.download = function(url, method, filedir, filename){
    jQuery('<form action="'+url+'" method="'+(method||'post')+'">' +  // action請求路徑及推送方法
                '<input type="text" name="filedir" value="'+filedir+'"/>' + // 檔案路徑
                '<input type="text" name="filename" value="'+filename+'"/>' + // 檔案名稱
            '</form>')
    .appendTo('body').submit().remove();
};           

複制

2. 查詢資料,輸出到檔案,儲存到伺服器,并調用download方法實作下載下傳

// 查詢資料,輸出到檔案,儲存到伺服器,并實作下載下傳
function exportOilDetection() {
    var ids = ['1','2','3','4']; // 查詢參數代表(可根據實際情況修改),需要導出資料的id
    $.ajax({
            type : 'POST',
            dataType : 'json',
            async : false,
            url : "${pageContext.request.contextPath}/oilDetectionAction!ajaxExportOilDetectionInfos.action", // 生成檔案,儲存在伺服器
            data : {
                ids : ids,
            },
            success : function(data) {
                var result = data["data"];
                if (result[0] == "success") {
                    // result[0] -- 檔案生成成功标記
                    // result[1] -- 路徑
                    // result[2] -- 檔案名稱
                    $.download('oilDetectionAction!ajaxDownloadDataExcel.action', 'post', result[1], result[2]); // 下載下傳檔案
                } else {
                    alert("資料導出失敗!");
                }
            },
            error : function(XMLHttpRequest, textStatus, e) {
                console.log("oilDetection.js  method exportOilDetection" + e);
            }
    });
}           

複制

action檔案配置

  • ajax生成檔案後,會傳回json類型結果
<action name="oilDetectionAction" class="oilDetectionAction">
            <result name="ajax" type="json">
                <param name="root">result</param>
            </result>
            <result name="success">/page/oilDetection.jsp</result>
        </action>           

複制

java代碼:

  • 傳回檔案流需借助response對象,是以action類需要實作ServletResponseAware接口,并聲明response對象自動注入
public class OilDetectionAction implements ServletResponseAware {
    
    HttpServletResponse response;
    
    /**
     * 自動注入response
     */
    public void setServletResponse(HttpServletResponse response) {
        this.response = response;
    }
    
     ....
}           

複制

  • 下載下傳檔案部分代碼:
public class OilDetectionAction implements ServletResponseAware {
    
     ....
     
    /**
     * 将生成的檔案網絡傳輸到用戶端
     */
    public void ajaxDownloadDataExcel() throws IOException {
        InputStream ins = null;
        BufferedInputStream bins = null;
        OutputStream outs = null;
        BufferedOutputStream bouts = null;
        String file_name = getRequest().getParameter("file_name").trim(); // 檔案名
        String file_dir = getRequest().getParameter("file_dir").trim(); // 檔案路徑
        System.out.println("擷取到檔案路徑:" + file_dir + File.separator + file_name);
        try {
            if (!"".equals(file_name)) {
                File file = new File(file_dir + File.separator + file_name);
                if (file.exists()) {
                    ins = new FileInputStream(file_dir + File.separator
                            + file_name);
                    bins = new BufferedInputStream(ins);
                    outs = response.getOutputStream();
                    bouts = new BufferedOutputStream(outs);
                    response.setContentType("application/x-download");
                    response.setHeader(
                            "Content-disposition",
                            "attachment;filename="
                                    + URLEncoder.encode(file_name, "UTF-8"));
                    int bytesRead = 0;
                    byte[] buffer = new byte[8192];
                    while ((bytesRead = bins.read(buffer, 0, 8192)) != -1) {
                        bouts.write(buffer, 0, bytesRead);
                    }
                    bouts.flush();
                } else {
                    throw new Exception("下載下傳的檔案不存在!");
                }
            } else {
                throw new Exception("導出檔案時發生錯誤!");
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            if (null != ins) {
                ins.close();
            }
            if (null != bins) {
                bins.close();
            }
            if (null != outs) {
                outs.close();
            }
            if (null != bouts) {
                bouts.close();
            }
        }
    }
}           

複制