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. Pandas高级教程之:稀疏数据结构

    目录 简介 Spare data的例子 SparseArray SparseDtype Sparse的属性 Sparse的计算 SparseSeries 和 SparseDataFrame 简介 如果 ...

  2. 备战-Java 并发

    备战-Java 并发 谁念西风独自凉,萧萧黄叶闭疏窗 简介:备战-Java 并发. 一.线程的使用 有三种使用线程的方法: 实现 Runnable 接口: 实现 Callable 接口: 继承 Thr ...

  3. python twain 扫描

    def multiScan(self): """ Scan and return an array of PIL objects If no images, will r ...

  4. Bat脚本备份sqlserver 表结构、存储过程、函数、指定表数据

    Bat脚本备份sqlserver 表结构.存储过程.指定表数据: @echo off cd /d %~dp0 ::备份表结构.存储过程和部分配置表的数据 set LogFile=report.log ...

  5. Python多线程爬取某网站表情包

    # 爬取网络图片import requestsfrom lxml import etreefrom urllib import requestfrom queue import Queue # 导入队 ...

  6. 关于 junit4 90% 的人都不知道的特性,详解 junitperf 的实现原理

    前言 上一节介绍了 https://github.com/houbb/junitperf 的入门使用. 这一节我们从源码的角度,剖析一下其实现方式. 性能测试该怎么做? Junit Rules jun ...

  7. 关键字替代符号C++

    不知从什么时候的哪里我看到了一个and关键字,心想这是个什么玩意...然后知道它相当于&&,于是开启了罪恶的生涯-- 替代关键字,似乎可读性更好,但是有些编译器可能会无法识别(eg.M ...

  8. spring boot+mybatis plus出现Invalid bound statement (not found)

    qlSessionFactory不要使用原生的,请使用MybatisSqlSessionFactory

  9. C++第五十二篇 -- 多线程之消息传递

    主线程向子线程发送消息 参考链接:https://www.cnblogs.com/ranjiewen/p/5729539.html 1. 创建线程语句 HANDLE hThread; DWORD dw ...

  10. navigator导航页面跳转与绑定事件

    效果图: 1. 新建一个index页面 主页面分为两块,上面是导航条,下面是轮播图. 导航条: <view class='menu'> <scroll-view scroll-x&g ...