Use java to complete the file download function

Implementation code

 @RequestMapping("/downtest")
    public void down(HttpServletResponse response) throws UnsupportedEncodingException {
    
    
        // 下载本地文件
        String fileName = new String("tt.xlsx"); // 文件的默认保存名
        // 读到流中
        InputStream inStream =this.getClass().getResourceAsStream("/static/test.xlsx"); // 文件的存放路径
        // 设置输出的格式
        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();
        }
    }

Insert picture description here
Insert picture description here
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_44067333/article/details/110713538