突然有个需求,需要从数据库获取数据,并生成文件下载。(很久没写都忘了,记录下)
1、我的伪代码是springboot+springmvc做的,项目结构:
1.1、项目依赖
1 <?xml version="1.0" encoding="UTF-8"?> 2 <project xmlns="http://maven.apache.org/POM/4.0.0" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 5 <modelVersion>4.0.0</modelVersion> 6 <!--SpringBoot的起步依赖spring-boot-starter-parent--> 7 <parent> 8 <groupId>org.springframework.boot</groupId> 9 <artifactId>spring-boot-starter-parent</artifactId> 10 <version>2.0.1.RELEASE</version> 11 </parent> 12 <groupId>com.springbootdemo</groupId> 13 <artifactId>springbootdemo</artifactId> 14 <version>1.0-SNAPSHOT</version> 15 <dependencies> 16 <!--web的启动依赖--> 17 <dependency> 18 <groupId>org.springframework.boot</groupId> 19 <artifactId>spring-boot-starter-web</artifactId> 20 </dependency> 21 <dependency> 22 <groupId>commons-io</groupId> 23 <artifactId>commons-io</artifactId> 24 <version>2.6</version> 25 </dependency> 26 <dependency> 27 <groupId>cn.hutool</groupId> 28 <artifactId>hutool-core</artifactId> 29 <version>5.3.3</version> 30 </dependency> 31 </dependencies> 33 </project>
1.2、启动类
1 package com.springboot.demo; 2 3 import org.springframework.boot.SpringApplication; 4 import org.springframework.boot.autoconfigure.SpringBootApplication; 5 6 /** 7 * @author dingpl 8 * @date 2021/7/13 10:22 9 */ 10 @SpringBootApplication 11 public class MySpringBootApplication { 12 public static void main(String[] args) { 13 SpringApplication.run(MySpringBootApplication.class); 14 } 15 }
1.3、默认访问index.html
1 package com.springboot.demo.controller; 2 3 import org.springframework.context.annotation.Configuration; 4 import org.springframework.core.Ordered; 5 import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; 6 import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; 7 8 /** 9 * @author dingpl 10 * @date 2021/7/13 10:24 11 */ 12 @Configuration 13 public class DemoController extends WebMvcConfigurerAdapter { 14 @Override 15 public void addViewControllers( ViewControllerRegistry registry ) { 16 registry.addViewController( "/" ).setViewName( "forward:/index.html" ); 17 registry.setOrder( Ordered.HIGHEST_PRECEDENCE ); 18 super.addViewControllers( registry ); 19 } 20 }
1.4、index页面
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="renderer" content="webkit"> <meta http-equiv="Cache-Control" content="no-siteapp"/> <title th:text="${titleName}">首页</title> </head> <body class="fixed-sidebar full-height-layout gray-bg" style="overflow: hidden"> <a id="download" href="/file/download" > <i class="fa fa-download"></i>下载test文件</a> </body> </html>
1.5、项目启动效果
1.6、这是我优化之后的文件下载controller
1 package com.springboot.demo.controller; 2 import com.springboot.demo.utils.PathUtils; 3 import org.springframework.stereotype.Controller; 4 import org.springframework.web.bind.annotation.RequestMapping; 5 import org.springframework.web.bind.annotation.RequestMethod; 6 import org.xml.sax.SAXException; 7 import org.apache.commons.io.FileUtils; 8 import java.io.*; 9 import javax.servlet.http.HttpServletResponse; 10 /** 11 * @author dingpl 12 * @date 2021/7/13 10:24 13 */ 14 @Controller 15 @RequestMapping("file") 16 public class FileController{ 17 18 @RequestMapping(value = "download",method = RequestMethod.GET) 19 public void download(HttpServletResponse response) throws SAXException { 20 String content = "null"; 21 String title = "test.xml"; 22 File xmlFile = null; 23 Writer out = null; 24 try { 25 File dic = new File(PathUtils.getRootPath() + "/file/tmpfile"); 26 if (!dic.exists()) { 27 dic.mkdirs(); 28 } 29 // 创建文件 30 xmlFile = new File(PathUtils.getRootPath() + "/file/tmpfile/"+title); 31 if (!xmlFile.exists()) { 32 xmlFile.createNewFile(); 33 } 34 //写入文件内容 35 out = new FileWriter(xmlFile); 36 out.write(content); 37 out.flush(); 38 out.close(); 39 response.reset(); 40 response.setContentType("application/octet-stream"); 41 //3.设置content-disposition响应头控制浏览器以下载的形式打开文件 42 response.setHeader("content-disposition", "attachment;filename=" + java.net.URLEncoder.encode(title, "UTF-8")); 43 // 输出文件 44 byte[] bytes = FileUtils.readFileToByteArray(xmlFile); 45 OutputStream outputStream = response.getOutputStream(); 46 outputStream.write(bytes);//将缓冲区的数据输出到客户端浏览器 47 } catch (Exception e) { 48 e.printStackTrace(); 49 } finally { 50 if (xmlFile.exists()) { 51 xmlFile.delete();//删除文件 52 } 53 } 54 55 } 56 }
1.7、因为创建文件会在项目中生成文件,我选择将文件放到临时文件夹
1 package com.springboot.demo.utils; 2 3 import java.io.File; 4 5 /** 6 * 在windows和linux系统下均可正常使用 7 * 8 */ 9 public class PathUtil { 10 //获取项目的根路径 11 public final static String classPath; 12 13 static { 14 //获取的是classpath路径,适用于读取resources下资源 15 // classPath = Thread.currentThread().getContextClassLoader().getResource("").getPath(); 16 classPath = System.getProperty("user.dir"); 17 } 18 19 /** 20 * 项目根目录 21 */ 22 public static String getRootPath() { 23 return RootPath(""); 24 } 25 26 /** 27 * 自定义追加路径 28 */ 29 public static String getRootPath(String u_path) { 30 return RootPath("/" + u_path); 31 } 32 33 /** 34 * 私有处理方法 35 */ 36 private static String RootPath(String u_path) { 37 String rootPath = ""; 38 //windows下 39 if ("\\".equals(File.separator)) { 40 //System.out.println(classPath); 41 rootPath = classPath + u_path; 42 rootPath = rootPath.replaceAll("/", "\\\\"); 43 if (rootPath.substring(0, 1).equals("\\")) { 44 rootPath = rootPath.substring(1); 45 } 46 } 47 //linux下 48 if ("/".equals(File.separator)) { 49 //System.out.println(classPath); 50 rootPath = classPath + u_path; 51 rootPath = rootPath.replaceAll("\\\\", "/"); 52 } 53 return rootPath; 54 } 55 56 //更多扩展方法任你发挥 57 58 }
1 package com.springboot.demo.utils; 2 import java.io.File; 3 import java.io.UnsupportedEncodingException; 4 import java.net.URLDecoder; 5 import java.nio.charset.StandardCharsets; 6 /** 7 * @author dingpl 8 * @date 2021/7/13 10:25 9 */ 10 public class PathUtils { 11 /** 12 * 如果已打成jar包,则返回jar包所在目录 13 * 如果未打成jar,则返回target所在目录 14 * @return 15 */ 16 public static String getRootPath() throws UnsupportedEncodingException { 17 // 项目的编译文件的根目录 18 String path = URLDecoder.decode(PathUtil.class.getResource("/").getPath(), String.valueOf(StandardCharsets.UTF_8)); 19 if (path.startsWith("file:")) { 20 int i = path.indexOf(".jar!"); 21 path = path.substring(0, i); 22 path = path.replaceFirst("file:", ""); 23 } 24 // 项目所在的目录 25 return new File(path).getParentFile().getAbsolutePath(); 26 } 27 28 }
至此代码完成!
效果图:
2.1、点击下载按钮
2.2、文件内容
期待大家的指正!!!
package com.springboot.demo.utils;
import java.io.File;
/**
* 在windows和linux系统下均可正常使用
*
*/
public class PathUtil {
//获取项目的根路径
public final static String classPath;
static {
//获取的是classpath路径,适用于读取resources下资源
// classPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
classPath = System.getProperty("user.dir");
}
/**
* 项目根目录
*/
public static String getRootPath() {
return RootPath("");
}
/**
* 自定义追加路径
*/
public static String getRootPath(String u_path) {
return RootPath("/" + u_path);
}
/**
* 私有处理方法
*/
private static String RootPath(String u_path) {
String rootPath = "";
//windows下
if ("\\".equals(File.separator)) {
//System.out.println(classPath);
rootPath = classPath + u_path;
rootPath = rootPath.replaceAll("/", "\\\\");
if (rootPath.substring(0, 1).equals("\\")) {
rootPath = rootPath.substring(1);
}
}
//linux下
if ("/".equals(File.separator)) {
//System.out.println(classPath);
rootPath = classPath + u_path;
rootPath = rootPath.replaceAll("\\\\", "/");
}
return rootPath;
}
//更多扩展方法任你发挥
}