参考 :
https://blog.csdn.net/qq_31940707/article/details/80405218
https://www.cnblogs.com/sunny3096/p/8204291.html
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
/**
* @Auther: liyue
* @Date: 2018/11/15 16:39
* @Description:
*/
@RestController
@RequestMapping("/download")
public class DownloadConroller {
@RequestMapping("/download_excel")
public void downloadExcel(String fileName, HttpServletResponse response) {
// 2.获取要下载的文件的绝对路径
File file = new File(fileName);
try {
// 3.设置content-disposition响应头控制浏览器以下载的形式打开文件
// 设置强制下载不打开
response.setContentType("application/force-download");
// 设置文件名
response.addHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "utf-8"));
// 4.根据文件路径获取要下载的文件输入流
InputStream in = new FileInputStream(file);
int len = 0;
// 5.创建数据缓冲区
byte[] buffer = new byte[1024];
// 6.通过response对象获取OutputStream流
OutputStream out = response.getOutputStream();
// 7.将FileInputStream流写入到buffer缓冲区
while ((len = in.read(buffer)) > 0) {
// 8.使用OutputStream将缓冲区的数据输出到客户端浏览器
out.write(buffer, 0, len);
}
in.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}