點選按鈕,實現檔案下載,通過按鈕傳送url,spring後臺實現伺服器端檔案下載。

Walter Sun發表於2018-04-25

頁面程式碼:

<button id="btn2" type="button" class="btn btn-primary" onclick="DownLoad()">下載</button>

頁面按鈕js程式碼:

function DownLoad(){ 
     window.open(url="http://localhost:8585/sm/sm/download");  
}

spring後臺下載功能程式碼:

需要設定請求頭,請求體。

然後使用輸入流讀取檔案,通過輸出流傳送檔案。

@RequestMapping("/sm/download")
    public void downLoad(String file, HttpServletRequest request,
            HttpServletResponse response) {
        String path = "F:\\MyEclipse 9Workspaces\\sm\\smfiledown\\";
        File ofile = new File(path);
        for (File p : ofile.listFiles()) {
            if (!p.isDirectory()) {
                String fname = p.getName();
                FileInputStream fs = null;
                if (p.exists()) {
                    // response.setContentType("application/force-download");
                    try {
                        response.setHeader(
                            "Content-Disposition",
                            "attachment;fileName="
                                    + new String(fname.getBytes("utf-8"),
                                            "iso_8859_1"));
                        fs = new FileInputStream(p);
                        byte[] buf = new byte[1024];
                        int len = 0;
                        ServletOutputStream o = response.getOutputStream();
                        while ((len = fs.read(buf)) != -1) {
                            o.write(buf, 0, len);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        request.setAttribute("error", " 쳣  ");
                    } finally {
                        try {
                            if (fs != null)
                                fs.close();
                        } catch (IOException e) {
                            request.setAttribute("error", " 쳣  ");
                        }
                    }
                   p.delete();
                    break;
                }
            }
        }
    }

 

相關文章