springboot下载TXT文件时会将后台返回的成功信息一并返回

springboot下载TXT文件时会将后台返回的成功信息一并返回
强烈推介IDEA2021.1.3破解激活,IntelliJ IDEA 注册码,2021.1.3IDEA 激活码  

大家好,我是架构君,一个会写代码吟诗的架构师。今天说一说springboot下载TXT文件时会将后台返回的成功信息一并返回,希望能够帮助大家进步!!!

public static void dowFile(String fileName, HttpServletResponse response) throws Exception {
        if (fileName != null) {
            //设置文件路径
            File file = new File(ClassUtils.getDefaultClassLoader().getResource("").getPath() + "static\\" + fileName);
                response.setContentType("application/force-download");// 设置强制下载不打开
                String jieguo = fileName.substring(fileName.indexOf("~") + 1);
                response.addHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(jieguo, "utf-8"));// 设置文件名
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                } catch (Exception e) {
                    throw new BusinessException("下载失败");
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            } else {
                throw new BusinessException("没有该文件");
            }

 

本文来源huayang183,由架构君转载发布,观点不代表Java架构师必看的立场,转载请标明来源出处:https://javajgs.com/archives/18239

发表评论