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. P4827「国家集训队」 Crash 的文明世界

    「国家集训队」 Crash 的文明世界 提供一种不需要脑子的方法. 其实是看洛谷讨论版看出来的( (但是全网也就这一篇这个方法的题解了) 首先这是一个关于树上路径的问题,我们可以无脑上点分治. 考虑当 ...

  2. 根据序列号查IP

    def getIP():#得到当前电脑IP import socket s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(( ...

  3. 高校表白App-团队冲刺第九天

    今天要做什么 在Fragment首页加上轮转播报,点击图片进入相应连接 做了什么 功能实现,通过连接第三方库来进行实现,比较简单.(url就可以) 遇到的问题 在调用以前的工具类时,有点小问题,发现以 ...

  4. File类与常用IO流第四章——IO字节流

    一切文件在存储时,都是以二进制数字的形式保存的,都是一个一个字节.无论使用什么样的流对象,底层传输的始终是二进制数据. 字节输出流 OutputStream java.io.OutputStream ...

  5. linux相关的常用站点

    1  http://cdimage.ubuntu.com/ ubuntu各个发行版的总集服务器 2 http://www.rpmfind.net/ 各种RPM包

  6. .net 5+ 知新:【1】 .Net 5 基本概念和开发环境搭建

    最近一两年搞了很多其它事情,.net web方面的基本没做,之前做过几个小的项目零星的学习了些,从.net core 发布后其实都没正真的系统学习过. 就是上手做项目,平时也有关注和看些资料,所以项目 ...

  7. Lniux上的tomcat部署web项目路径问题

    一.项目路径及部署.启动位置 1.在tomcat下部署应用,部署路径:一般直接部署在tomcat/webapps/ROOT下即可.2.默认访问路径:tomcat的默认访问路径为webapps/ROOT ...

  8. 用Pygal画一个英雄能力的图

    效果图: 这是在google浏览器下打开的html. play.py #!/usr/bin/env python # _*_ coding: UTF-8 _*_ """= ...

  9. Tomcat 性能监控与优化

    JMX JMX(Java Management Extensions)是一个为应用程序植入管理功能的框架.JMX是一套标准的 代理和服务,实际上,用户可以在任何Java应用程序中使用这些代理和服务实现 ...

  10. Excel VBA活动抽奖小程序

    在活动中,我们常会有抽奖,抽奖箱准备繁琐,现在多采用线上抽奖方式,下面用Excel VBA写了一个简单的抽奖小程序 简单测试效果如下,可实现: 多次抽奖,且每次抽奖都不重复 抽奖界面滚动人员信息,点击 ...