其实文件下载,不太建议用接口做,因为文件下载一般都是下载一些静态文件,我们可以先将文件处理好,然后通过Nginx 服务下载静态文件,这样速度会快很多。但是这里我们还是写一下。代码也很简单,就一个方法,也写在Controller 类中
package com.chongdian.api.controller;
import com.chongdian.api.core.http.ResultResponse;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
/**
* DownLoadController
*
* @author: RunZe
* @date: 2020/7/10 15:32
*/
@RequestMapping("/home")
@RestController
public class DownLoadController {
private static final String filepath = getResourceBasePath() + "/upload/";
@RequestMapping("/download")
public String fileDownLoad(HttpServletResponse response, @RequestParam("fileName") String fileName){
File file = new File(filepath + '/' + fileName);
if(!file.exists()){
return "下载文件不存在";
}
response.reset();
response.setContentType("application/octet-stream");
response.setCharacterEncoding("utf-8");
response.setContentLength((int) file.length());
response.setHeader("Content-Disposition", "attachment;filename=" + fileName );
try(BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));) {
byte[] buff = new byte[1024];
OutputStream os = response.getOutputStream();
int i = 0;
while ((i = bis.read(buff)) != -1) {
os.write(buff, 0, i);
os.flush();
}
} catch (IOException e) {
return "下载失败";
}
return "下载成功";
}
/**
* 获取项目根路径
*
* @return
*/
private static String getResourceBasePath() {
// 获取跟目录
File path = null;
try {
path = new File(ResourceUtils.getURL("classpath:").getPath());
} catch (FileNotFoundException e) {
// nothing to do
}
if (path == null || !path.exists()) {
path = new File("");
}
String pathStr = path.getAbsolutePath();
// 如果是在eclipse中运行,则和target同级目录,如果是jar部署到服务器,则默认和jar包同级
pathStr = pathStr.replace("\\target\\classes", "");
return pathStr;
}
}
测试的话也简单,我们启动项目,访问接口
http://localhost:8085/home/download?fileName=e9277dde-29c2-4805-a71a-3ea93d04d833.png