记录自己的写代码的过程,加油!
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
/**
* @ClassName ceshi
* @Deacription
* @Author YJT
* @Date 2020/11/3 14:48
* @Effect:
**/
@RestController
@RequestMapping("/download")
public class ceshi {
@RequestMapping(value = "/downloadExistFile")
public void downloadExistFile(HttpServletResponse response,String filePath,String fileName) {
FileInputStream fileInputStream = null;
ServletOutputStream servletOutputStream = null;
//http://localhost:8081/download/downloadExistFile
// String filePath = "E:\\test\\test\\123.pdf";
int indez;
indez = filePath.lastIndexOf(".");
String suffix = filePath.substring(indez);
String name = fileName+suffix;
try {
response.setContentType("application/x-msdownload;");
response.setHeader("Content-disposition", "attachment; filename=" + new String(name.getBytes("UTF-8"), "ISO-8859-1"));
// 将本地文件装载到内存
fileInputStream = new FileInputStream(filePath);
// 实例化输出流
servletOutputStream = response.getOutputStream();
byte[] buff = new byte[2048];
int bytesRead;
// 每次尝试读取buff.length长字节,直到读完、bytesRead为-1
while ((bytesRead = fileInputStream.read(buff, 0, buff.length)) != -1) {
// 每次写bytesRead长字节
servletOutputStream.write(buff, 0, bytesRead);
}
// 刷新缓冲区
servletOutputStream.flush();
} catch (IOException e) {
e.fillInStackTrace();
} finally {
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {
e.fillInStackTrace();
}
}
if (servletOutputStream != null) {
try {
servletOutputStream.close();
} catch (IOException e) {
e.fillInStackTrace();
}
}
}
}
}