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("下载中药饮片导入模板失败,请联系管理员!");
		}
	}
相关推荐
ybq195133454315 分钟前
Redis-主从复制-分布式系统
java·数据库·redis
weixin_4723394636 分钟前
高效处理大体积Excel文件的Java技术方案解析
java·开发语言·excel
小毛驴8501 小时前
Linux 后台启动java jar 程序 nohup java -jar
java·linux·jar
枯萎穿心攻击1 小时前
响应式编程入门教程第二节:构建 ObservableProperty<T> — 封装 ReactiveProperty 的高级用法
开发语言·unity·c#·游戏引擎
DKPT2 小时前
Java桥接模式实现方式与测试方法
java·笔记·学习·设计模式·桥接模式
Eiceblue3 小时前
【免费.NET方案】CSV到PDF与DataTable的快速转换
开发语言·pdf·c#·.net
好奇的菜鸟3 小时前
如何在IntelliJ IDEA中设置数据库连接全局共享
java·数据库·intellij-idea
m0_555762903 小时前
Matlab 频谱分析 (Spectral Analysis)
开发语言·matlab
DuelCode4 小时前
Windows VMWare Centos Docker部署Springboot 应用实现文件上传返回文件http链接
java·spring boot·mysql·nginx·docker·centos·mybatis
浪裡遊4 小时前
React Hooks全面解析:从基础到高级的实用指南
开发语言·前端·javascript·react.js·node.js·ecmascript·php