【java文件处理】java项目路径下的文件下载处理
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项目路径下的文件下载处理的更多相关文章
- java 压缩文件 传入文件数组,压缩文件,在指定路径下生成指定文件名的压缩文件
/** * 传入文件数组,压缩文件,在指定路径下生成指定文件名的压缩文件 * * @param files * 文件数组 * @param strZipName * 压缩文件路径及文件名 * @thr ...
- 夯实Java基础系列5:Java文件和Java包结构
目录 Java中的包概念 包的作用 package 的目录结构 设置 CLASSPATH 系统变量 常用jar包 java软件包的类型 dt.jar rt.jar *.java文件的奥秘 *.Java ...
- Java文件和Java包结构
Java中的包概念 Java中的包是封装一组类,子包和接口的机制.软件包用于: 防止命名冲突.例如,可以有两个名称分别为Employee的类,college.staff.cse.Employee和co ...
- tomcat中实现特定路径下的图片的url访问Tomcat配置图片保存路径,图片不保存在项目路径下
使用Tomcat作为服务器的时候,如果不配置图片保存路径,将图片保存在项目路径下,那么再次打war包发布项目可能会造成图片的丢失,每次重启前将图片先保存再copy到服务器明显不方便,这时可以配置图片保 ...
- C#实现把指定文件夹下的所有文件复制到指定路径下以及修改指定文件的后缀名
1.实现把指定文件夹下的所有文件复制到指定路径下 public static void copyFiles(string path) { DirectoryInfo dir = new Directo ...
- Java获取程序或项目路径的常用方法
在写java程序时不可避免要获取文件的路径,比较常用的方法有: 1 在任意的class里调用: this.getClass().getClassLoader().getResource("/ ...
- Java扫描classpath指定包路径下所有class
在写框架时 经常需要扫描classpath指定包路径下带有某个Annotation的类,自己整理了一下 封装成一个工具类了,供大家参考. 源代码ClassPathResourceScanner.jav ...
- 怎样把.git版本控制文件夹放在项目目录下
在上传本地代码到本地git库时,.git的存放目录不能放到项目根目录下(报错). 可以先把.git仓库选择其他保存路径,然后再copy到项目根目录下.
- java读取项目路径下的中文文件乱码问题
出现乱码错误: 处理方案: 对文件路径中存在中文的,都要进行URLDecoder.decode(path,"UTF-8")编码转换 wordContent = URLEncoder ...
随机推荐
- 剖析:如何用 SwitchUI 5天写一个微信 —— 聊天界面篇
前置资源 GitHub: SwiftUI-WeChatDemo 第零章:用 SwiftUI 五天组装一个微信 - wavky - 博客园 整体结构 UI 部分代码分布如上图所示,App 的主入口类为 ...
- Python中字典get方法的使用技巧
get方法,用于获取字典中某个键值key 对应value的值,此方法可以接收两个参数,第一个参数传入key的值,第二个参数用于传入一个自定义返回值,如果查询的key在字典中存在,就会反回对应key在字 ...
- war项目依赖war项目
还没有看,立个flag:https://my.oschina.net/u/588379/blog/1817077
- linux相关的常用站点
1 http://cdimage.ubuntu.com/ ubuntu各个发行版的总集服务器 2 http://www.rpmfind.net/ 各种RPM包
- 单细胞分析实录(19): 基于CellPhoneDB的细胞通讯分析及可视化 (下篇)
在上一篇帖子中,我介绍了CellPhoneDB的原理.实际操作,以及一些值得注意的地方.这一篇继续细胞通讯分析的可视化. 公众号后台回复20210723获取本次演示的测试数据,以及主要的可视化代码. ...
- FastDFS是使用c语言编写的开源高性能分布式文件系统
FastDFS是什么 FastDFS是使用c语言编写的开源高性能分布式文件系统 是由淘宝开发平台部资深架构师余庆开发,FastDFS孵化平台板块 他对文件进行管理,功能包括文件存储,文件同步,文件访问 ...
- Python基础之tabview
以前写过界面,但是没有记录下来,以至于现在得从头学习一次,论做好笔记的重要性. 现在学习的是怎么写一个tabview出来,也就是用tkinter做一个界面切换的效果.参考链接:https://blog ...
- js学习笔记之公告逐行显示
$(function(){ var newsListHeight = $(".news-list").height(); //获得内容的高度 var newsConHeight = ...
- 就这?Spring 事务失效场景及解决方案
小明:靓仔,我最近遇到了很邪门的事. 靓仔:哦?说来听听. 小明:上次看了你的文章<就这?一篇文章让你读懂 Spring 事务>,对事务有了详细的了解,但是在项目中还是遇到了问题,明明加了 ...
- 【算法学习笔记】动态规划与数据结构的结合,在树上做DP
前置芝士:Here 本文是基于 OI wiki 上的文章加以修改完成,感谢社区的转载支持和其他方面的支持 树形 DP,即在树上进行的 DP.由于树固有的递归性质,树形 DP 一般都是递归进行的. 基础 ...