点击按钮,实现文件下载,通过按钮发送url,spring后台实现服务器端文件下载。

页面代码:

页面按钮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;
                }
            }
        }
    }

 
 

你可能感兴趣的:(JavaEE开发)