java download: Download the file from the project

Download the file to a page, file download

Note: The actual development of the vast majority of cases are stored in a separate file server, but there will be some small files can be stored in the project, in the project directory stored here, in fact, the code is similar, almost no difference
directly on the code :

 @RequestMapping("/down")
    @ResponseBody
    public void down(@RequestParam String id, HttpServletResponse response) throws FileNotFoundException, UnsupportedEncodingException {
        // 下载本地文件
        String fileName = new String("文件名.docx"); // 文件的默认保存名
        // 读到流中
        InputStream inStream =this.getClass().getResourceAsStream("/static/template/文件名.docx"); // 文件的存放路径
        // 设置输出的格式
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "utf-8"));
        // 循环取出流中的数据
        byte[] b = new byte[100];
        int len;
        try {
            while ((len = inStream.read(b)) > 0) {
                response.getOutputStream().write(b, 0, len);
            }
            inStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
Released seven original articles · won praise 1 · views 131

Guess you like

Origin blog.csdn.net/qq_42663973/article/details/104046298