1、后台下载文件比较简单的逻辑步骤
(1)、准备静态模板文件:把静态资源文件放到src/main/resource路径下,如:excelTmp/studentDemo.xlsx
(2)、实现逻辑:先获取静态资源的url路径,方法两种,但各有些小问题
第一种:
import java.net.URL; import org.springframework.core.io.ClassPathResource;
URL url = new ClassPathResource("excelTmp/studentDemo.xlsx").getURL();
这种方法在参数的路径上,不能包含中文(实现功能可以,推荐使用)
第二种:
URL url = getClass().getClassLoader().getResource("excelTmp/学生模板.xlsx");
这种方法在本地tomcat运行可以准确的获取静态资源文件,但亲测在linux服务器上获取的url为null(本人的测试的项目,调用处被打包在lib下的jar包中,对于存在一些特殊情况下会出问题,因此,不推荐使用)
(3)、获取资源后见的url后,获取文件,转文件的字节数组,通过respone的输出流,将文件字节数组输出
(4)、前端通过a标签,将href指定为接口地址,即可实现下载文件的效果(所以要求可以get请求)
(5)、调用实现详细代码如下
import com.hx.platform.annotation.BusiAnnotation;
import com.hx.platform.education168.ptgl.common.util.FileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLEncoder;
@RestController
@RequestMapping("/eduStudent")
@BusiAnnotation(busiModule = "学生管理")
public class StudentController {
// 日志
private static Logger logger = LoggerFactory.getLogger(StudentController.class);
@RequestMapping("/downloadExcel11")
public void testStream11(String excelType, HttpServletRequest req, HttpServletResponse resp) {
try {
URL url = null;
if("1".equals(excelType)){
url = getClass().getClassLoader().getResource("excelTmp/学生模板.xlsx");
} else if("2".equals(excelType)) {
url = getClass().getClassLoader().getResource("excelTmp/家长模板.xlsx");
} else if("3".equals(excelType)) {
url = getClass().getClassLoader().getResource("excelTmp/教师模板.xlsx");
}
logger.info("url:" + url);
// 通过url获取File的绝对路径
File f = new File(url.getFile());
resp.setCharacterEncoding("UTF-8");
resp.setContentType("application/x-download;charset=utf-8");
resp.setHeader("Content-disposition", URLEncoder.encode(f.getName(), "UTF-8"));
//mime类型
resp.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
resp.setHeader("Content-disposition", "attachment;filename="+URLEncoder.encode(f.getName(), "UTF-8"));
resp.setHeader("Pragma", "No-cache");
//从内存中写出来
OutputStream outputStream = resp.getOutputStream();
outputStream.write(FileUtil.file2byte(f));
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
@RequestMapping("/downloadExcel")
public void testStream(String excelType, HttpServletRequest req, HttpServletResponse resp) {
try {
URL url = null;
if("1".equals(excelType)){
url = new ClassPathResource("excelTmp/studentDemo.xlsx").getURL();
} else if("2".equals(excelType)) {
url = new ClassPathResource("excelTmp/parentDemo.xlsx").getURL();
} else if("3".equals(excelType)) {
url = new ClassPathResource("excelTmp/teacherDemo.xlsx").getURL();
}
logger.info("url:" + url);
// 通过url获取File的绝对路径
File f = new File(url.getFile());
resp.setCharacterEncoding("UTF-8");
resp.setContentType("application/x-download;charset=utf-8");
resp.setHeader("Content-disposition", URLEncoder.encode(f.getName(), "UTF-8"));
//mime类型
resp.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
resp.setHeader("Content-disposition", "attachment;filename="+URLEncoder.encode(f.getName(), "UTF-8"));
resp.setHeader("Pragma", "No-cache");
//从内存中写出来
OutputStream outputStream = resp.getOutputStream();
outputStream.write(FileUtil.file2byte(f));
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
附:文件转字节数组代码
import java.io.*;
/**
* 用于文件和流转换需要
*/
public class FileUtil {
/**
* 将文件转换成byte数组
* @param
* @return
*/
public static byte[] file2byte(File tradeFile){
byte[] buffer = null;
try
{
FileInputStream fis = new FileInputStream(tradeFile);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int n;
while ((n = fis.read(b)) != -1)
{
bos.write(b, 0, n);
}
fis.close();
bos.close();
buffer = bos.toByteArray();
}catch (FileNotFoundException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
return buffer;
}
}
(6)、测试效果:
(7)、以上下载模板文件成功,总结就是后端获取静态文件,转文件流通过浏览器响应参数response来输出文件流,前端通过a标签来触发即可。学海无涯苦作舟!