废话不多说,直接上代码,拷贝即可用~~~
项目结构:

下载工具类:
/**
* @program: myutil
* @description: 从本地项目(本地磁盘上)下载静态文件
* @author: lsy
* @create: 2020-08-13 16:58
**/
public class LocalFileUtils {
/**
* @param response
* @param fileName
* @description 根据指定项目路径下的某个excel, 下载文件
*/
public static void exportFile(HttpServletResponse response, String fileName) {
// 第一种获取静态资源
ClassPathResource classPathResource = new ClassPathResource("static/excleTemplate/" + fileName);// "static/excleTemplate/ImportModel.xlsx"
// 第二种获取静态资源
// InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("static/excleTemplate/" + fileName);
// 第三种获取静态资源
// InputStream inputStream = this.getClass().getResourceAsStream("static/excleTemplate/" + fileName);
InputStream inputStream = null;
OutputStream outputStream = null;
try {
inputStream = classPathResource.getInputStream();
outputStream = response.getOutputStream();
int BUFFER_SIZE = 1024 * 4;
byte[] buffer = new byte[BUFFER_SIZE];
int reader = 0;
while ((reader = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, reader);
}
response.setContentType("application/octet-stream");
response.setCharacterEncoding("utf-8");
String newFileName = URLEncoder.encode(classPathResource.getFilename(), "UTF-8");
response.setHeader("Content-disposition", "attachment;filename=" + newFileName);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (outputStream != null) {
/**flush():仅仅刷新缓冲区(一般写字符时要用,因为字符时先进入缓冲区),然后将内存中的数据立刻写出(因为缓冲区是装满之后才会写出
,用flush()就不必等到缓冲区满,立刻写出,流对象还可以继续使用) */
outputStream.flush();
/**close():关闭流对象. 也会先刷新一次缓冲区,再关闭. 关闭之后,流对象不可以继续使用 */
outputStream.close();
inputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
控制器:
@ApiOperation(value = "获取resource下附件")
@GetMapping(value = "/exportFile")
public void exportFile(String fileName, HttpServletResponse response) {
// fileName = "ImportModel.xlsx";
fileName = "labixiaoxin.jpg";
LocalFileUtils.exportFile(response, fileName);
}
如有转载,请标明出处!
本文提供了一个简单的Java代码示例,用于在项目中下载静态文件。通过一个下载工具类和控制器的配合,可以方便地实现文件的下载功能。请确保在使用时注明来源。
21万+





