1. controller类:

package com.neo.controller;

import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* 通用文件处理controller
* @author wjqhuaxia
*/
@RestController
@RequestMapping("/generalFile")
public class GeneralFileController { /**
* 模版文件下载
* @param fileType 文件类型 对应 TemplateFileTypeEnum 的key
* @param notIE 是否IE浏览器,true是,false不是
* @return
*/
@GetMapping("/downTemplate/{fileType}/{notIE}")
public String downTemplate(HttpServletResponse response,
@PathVariable String fileType, @PathVariable boolean notIE){
TemplateFileTypeEnum fileTypeEnum = TemplateFileTypeEnum.getEnum(fileType);
FileUtils.downloadFile(response, fileTypeEnum, notIE);
return "下载成功!";
} // 测试:http://localhost:8080/generalFile/downTemplate/test/false
}

2. 文件工具类

package com.neo.controller;

import java.io.BufferedInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException; import javax.servlet.http.HttpServletResponse; import org.springframework.core.io.ClassPathResource; /**
* 文件工具类
* @author wjqhuaxia
*/
public class FileUtils { /**
* 下载项目根目录下doc下的文件
* @param response response
* @param fileName 文件名
* @param notIE 是否IE浏览器,true是,false不是
* @return 返回结果 成功或者文件不存在
*/
public static String downloadFile(HttpServletResponse response, TemplateFileTypeEnum fileTypeEnum, boolean notIE) {
String fileName = fileTypeEnum.getFileName();
String filePath = fileTypeEnum.getFilePath();
String contentType = fileTypeEnum.getContentType(); ClassPathResource classPathResource = new ClassPathResource(filePath + fileName);
InputStream stream = null;
try {
stream =classPathResource.getInputStream();
} catch (IOException e3) {
e3.printStackTrace();
}
response.setHeader("content-type", "application/octet-stream");
response.setContentType(contentType);
try {
String name = java.net.URLEncoder.encode(fileName, "UTF-8");
if (notIE) {
name = java.net.URLDecoder.decode(name, "ISO-8859-1");
}
response.setHeader("Content-Disposition", "attachment;filename=" + name );
} catch (UnsupportedEncodingException e2) {
e2.printStackTrace();
}
byte[] buff = new byte[1024];
BufferedInputStream bis = null;
OutputStream os = null;
try {
os = response.getOutputStream();
bis = new BufferedInputStream(stream);
int i = bis.read(buff);
while (i != -1) {
os.write(buff, 0, buff.length);
os.flush();
i = bis.read(buff);
}
} catch (FileNotFoundException e1) {
//e1.getMessage()+"系统找不到指定的文件";
return "系统找不到指定的文件";
}catch (IOException e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return "success";
}
}

3. 枚举类

package com.neo.controller;
/**
* 模版文件类型枚举类
* @author wjqhuaxia
*/
public enum TemplateFileTypeEnum { /**
* 测试试例
*/
TEMPLATE_TEST("test","测试模版.xlsx","static/templates/","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); private TemplateFileTypeEnum(String fileType,String fileName,
String filePath,String contentType){
this.contentType = contentType;
this.fileName = fileName;
this.fileType = fileType;
this.filePath = filePath;
} /**
* 文件类型
*/
private String fileType;
/**
* 文件名
*/
private String fileName;
/**
* 文件所在项目路径的位置
*/
private String filePath;
/**
* response中设置的contentType
*/
private String contentType; public String getFileType() {
return fileType;
}
public String getFileName() {
return fileName;
}
public String getFilePath() {
return filePath;
}
public String getContentType() {
return contentType;
}
/**
* 通过文件类型获取对应枚举
* @param fileType 文件类型
* @return
*/
public static TemplateFileTypeEnum getEnum(String fileType){
TemplateFileTypeEnum[] values = TemplateFileTypeEnum.values();
for (TemplateFileTypeEnum templateFileTypeEnum : values) {
if(templateFileTypeEnum.getFileType().equals(fileType)){
return templateFileTypeEnum;
}
}
return null;
}
}

  说明:

    一、如果只是需要进行简单的静态资源访问,直接使用springboot提供的机制即可,不需要动代码。

      可参考: https://www.cnblogs.com/gu-bin/p/11129066.html

    二、案例中的文件路径如下:

    

本案例参考:

  https://blog.csdn.net/weixin_33915554/article/details/91710148   ---  SpringBoot读取Resource下文件的几种方式

  https://blog.csdn.net/liubin5620/article/details/79530490  --- Spring Boot项目实现下载项目根目录下指定目录(doc)里的文件

  https://blog.csdn.net/xiaoyu19910321/article/details/79279364 --- 常见 content-type对应表

【java文件处理】java项目路径下的文件下载处理的更多相关文章

  1. java 压缩文件 传入文件数组,压缩文件,在指定路径下生成指定文件名的压缩文件

    /** * 传入文件数组,压缩文件,在指定路径下生成指定文件名的压缩文件 * * @param files * 文件数组 * @param strZipName * 压缩文件路径及文件名 * @thr ...

  2. 夯实Java基础系列5:Java文件和Java包结构

    目录 Java中的包概念 包的作用 package 的目录结构 设置 CLASSPATH 系统变量 常用jar包 java软件包的类型 dt.jar rt.jar *.java文件的奥秘 *.Java ...

  3. Java文件和Java包结构

    Java中的包概念 Java中的包是封装一组类,子包和接口的机制.软件包用于: 防止命名冲突.例如,可以有两个名称分别为Employee的类,college.staff.cse.Employee和co ...

  4. tomcat中实现特定路径下的图片的url访问Tomcat配置图片保存路径,图片不保存在项目路径下

    使用Tomcat作为服务器的时候,如果不配置图片保存路径,将图片保存在项目路径下,那么再次打war包发布项目可能会造成图片的丢失,每次重启前将图片先保存再copy到服务器明显不方便,这时可以配置图片保 ...

  5. C#实现把指定文件夹下的所有文件复制到指定路径下以及修改指定文件的后缀名

    1.实现把指定文件夹下的所有文件复制到指定路径下 public static void copyFiles(string path) { DirectoryInfo dir = new Directo ...

  6. Java获取程序或项目路径的常用方法

    在写java程序时不可避免要获取文件的路径,比较常用的方法有: 1 在任意的class里调用: this.getClass().getClassLoader().getResource("/ ...

  7. Java扫描classpath指定包路径下所有class

    在写框架时 经常需要扫描classpath指定包路径下带有某个Annotation的类,自己整理了一下 封装成一个工具类了,供大家参考. 源代码ClassPathResourceScanner.jav ...

  8. 怎样把.git版本控制文件夹放在项目目录下

    在上传本地代码到本地git库时,.git的存放目录不能放到项目根目录下(报错). 可以先把.git仓库选择其他保存路径,然后再copy到项目根目录下.

  9. java读取项目路径下的中文文件乱码问题

    出现乱码错误: 处理方案: 对文件路径中存在中文的,都要进行URLDecoder.decode(path,"UTF-8")编码转换 wordContent = URLEncoder ...

随机推荐

  1. Java基础00-面向对象基础13

    1. 类和对象 1.1 什么是对象 1.2 什么是面向对象                1.3 什么是类 1.4 什么是对象的属性 1.5 什么是对象的行为 行为就是对象能够干什么 1.6 类和对象 ...

  2. 使用python对工作簿每个sheet表进行数据可视化展示(本案例是从第2个sheet开始循环读取也就是索引为1的表)

    # 导入相关模块from pyecharts.charts import Barfrom pyecharts import options as optsfrom pyecharts.charts i ...

  3. 记一次系统崩溃事件【Mac版】

    事件:Mac系统崩溃,导致电脑数据丢失,以及数据安全备份措施的不到位的教训! 解决措施: 1.开机后按:Command+R 按开机键 ,进入Mac 实用工具, 选择磁盘工具.由于没有备份直接抹掉磁盘. ...

  4. linux 之awk--格式化文本信息

    https://www.cnblogs.com/xudong-bupt/p/3721210.html awk是行处理器: 相比较屏幕处理的优点,在处理庞大文件时不会出现内存溢出或是处理缓慢的问题,通常 ...

  5. xmind2020 zen 10.2.1win/mac/linux安装教程

    xmind是一款优秀的思维导图软件,本文教大家如何安装xmind zen 2020 10.2.1版本,解锁使用全部功能,包括去掉xmind zen水印.上传图片等功能,支持windows/mac/li ...

  6. JS对DOM的操作优化法则

    html页面显示过程 解析HTML,并生成一棵DOM tree 解析各种样式并结合DOM tree生成一棵Render tree 对Render tree的各个节点计算布局信息,比如box的位置与尺寸 ...

  7. IDEA使用Tomcat时控制台乱码的解决方案>从零开始学JAVA系列

    IDEA使用Tomcat时控制台乱码的解决方案 解决方案1,修改启动时虚拟机参数 解决方案2,修改idea的设置 解决方案3,修改idea配置文件 在最后添加一行 '-Dfile.encoding=U ...

  8. 在Windows中安装PySpark环境

    在Windows中安装PySpark环境 安装Python 可以选择安装官方版本的Python,或是Anaconda,对应的地址如下. 下载地址 Python:https://www.python.o ...

  9. 表单验证插件jquery-validation以及案例

    表单验证插件jquery-validation以及案例 1,获取并引入: (1)获取:官网:https://jqueryvalidation.org/ [home]->[files]->[ ...

  10. js绕过-前端加密绕过

    前端加密解密 目录 前端加密解密 前言 前端加密定位方法 加密绕过实例 其他情况 前言 日常我们在工作时做安全测试或者日常的漏洞挖掘中,往往会遇到请求加密,参数加密的情况,而且绝大部分都是前端加密的情 ...