Java从resources文件下载文档,文档没有后缀名

业务场景:因为公司会对excel文档加密,通过svn或者git上传代码也会对文档进行加密,所以这里将文档后缀去了,这样避免文档加密。

实现思路:将文档去掉后缀,放入resources下,获取输入流,最后加上后缀,前端成功下载

效果图

上代码

java 复制代码
package com.***.util;

import cn.hutool.core.util.StrUtil;
import org.springframework.core.io.ClassPathResource;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

/**
 * @author longwei
 * @Description excel帮助类
 * @date 2023/8/30 14:36
 */
public class ExcelUtils {

    /**
     * 从静态资源下载文件
     *
     * @param fileName 文件名,没有后缀
     * @param suffix   文件后缀
     * @param request  request
     * @param response response
     */
    public static void downloadFileByLocalPath(HttpServletRequest request, HttpServletResponse response,
                                               String fileName, String suffix) throws Exception {
        if (StrUtil.isEmpty(fileName) || StrUtil.isEmpty(suffix)) {
            throw new RuntimeException("文件信息不能为空");
        }
        InputStream inputStream = new ClassPathResource("file" + File.separator + fileName).getInputStream();
        fileName = fileName + suffix;
        downFileByInputStream(request, response, inputStream, fileName);
    }

    public static void downFileByInputStream(HttpServletRequest request, HttpServletResponse response, InputStream inputStream, String fileName) throws Exception {
        byte[] buffer = new byte[1024];
        BufferedInputStream bis = null;
        OutputStream os = null;
        String finalFileName;
        try {
            final String userAgent = request.getHeader("USER-AGENT");
            //IE浏览器
            if (StrUtil.contains(userAgent, "MSIE") || StrUtil.contains(userAgent, "Trident")) {
                finalFileName = URLEncoder.encode(fileName, "UTF8");
            }
            //google,火狐浏览器
            else if (StrUtil.contains(userAgent, "Mozilla")) {
                finalFileName = new String(fileName.getBytes(), "ISO8859-1");
            }
            //其他浏览器
            else {
                finalFileName = URLEncoder.encode(fileName, "UTF8");
            }
            response.setCharacterEncoding("UTF-8");
            // 设置强制下载不打开
            response.setContentType("application/force-download");
            // 设置文件名
            response.addHeader("Content-Disposition", "attachment;fileName=" + finalFileName);
            bis = new BufferedInputStream(inputStream);
            os = response.getOutputStream();
            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = bis.read(buffer);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (bis != null) {
                try {
                    bis.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (os != null) {
                try {
                    os.flush();
                    os.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

}

controller层

java 复制代码
    @RequestMapping("/downloadTemplate")
    public void downloadTemplate(HttpServletRequest request, HttpServletResponse response) {
        breedInfoService.downloadTemplate(request, response);
    }

service.impl层,这里直接用ExcelUtils方法

java 复制代码
	@Override
	public void downloadTemplate(HttpServletRequest request, HttpServletResponse response) {
		String fileName = "中药饮片导入模板";
		try {
			ExcelUtils.downloadFileByLocalPath(request, response, fileName, ".xlsx");
		} catch (Exception e) {
			log.error("下载中药饮片导入模板失败-{}", e.getMessage());
			throw new BusinessException("下载中药饮片导入模板失败,请联系管理员!");
		}
	}
相关推荐
一 乐20 分钟前
英语词汇小程序小程序|英语词汇小程序系统|基于java的四六级词汇小程序设计与实现(源码+数据库+文档)
java·数据库·小程序·源码·notepad++·英语词汇
Tech_gis23 分钟前
C++ 观察者模式
开发语言·c++·观察者模式
卑微求AC23 分钟前
继电器原理及应用
c语言·开发语言·51单片机·嵌入式
曳渔30 分钟前
Java-数据结构-反射、枚举 |ू・ω・` )
java·开发语言·数据结构·算法
laocooon52385788631 分钟前
java 模拟多人聊天室,服务器与客户机
java·开发语言
风槐啊32 分钟前
六、Java 基础语法(下)
android·java·开发语言
苹果醋337 分钟前
毕业设计_基于SpringBoot+vue的社区博客系统【源码+SQL+教程+可运行】41002
java·毕业设计·博客
网安老伯1 小时前
【2024版】最新kali linux入门及常用简单工具介绍(非常详细)零基础入门到精通,收藏这一篇就够了_kalilinux
linux·运维·服务器·开发语言·web安全·网络安全·xss
冬天vs不冷1 小时前
SpringBoot基础(四):bean的多种加载方式
java·spring boot·spring
说书客啊1 小时前
计算机毕业设计 | SpringBoot+vue学生成绩管理系统教务管理系统
java·spring boot·node.js·vue·毕业设计·课程设计·教务管理系统