下载项目下的文件

下载项目下的文件

    /**
     * 下载文件.
     * @param response 响应
     */
    @Override
    public void downLoadFile(HttpServletResponse response) {

        String fileName = "文件名" + ".doc";
        FileInputStream fin = null;
        ServletOutputStream out = null;
        //文件保存在src/main/resource文件夹下
        //第一种
        URL url = new ClassPathResource("file/Protocol.doc").getUrl();
        File file = new File(url.getFile());
        //第二种
        //File file = new File("./src/main/java/cn/bk/application/signapp/service/cert/file/" + "Protocol.doc");
        try {
            fin = new FileInputStream(file);
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/msword");
            response.setHeader("Content-Disposition", "attachment;filename*=utf-8''"
                    .concat(String.valueOf(URLEncoder.encode(fileName, "UTF-8"))));
            out = response.getOutputStream();
            // 缓冲区
            byte[] buffer = new byte[1024];
            int bytesToRead = -1;
            // 通过循环将读入的Word文件的内容输出到浏览器中
            while ((bytesToRead = fin.read(buffer)) != -1) {
                out.write(buffer, 0, bytesToRead);
            }
        } catch (IOException exception) {
            exception.printStackTrace();
        }

    }
上一篇:实验七


下一篇:2021高频PHP面试题(值得收藏)