1,利用io流下载文件
@RestController
public class FileController {
@GetMapping (value = "download")
public String download(HttpServletResponse response, Model model) {
String URL = "C:/Users/Administrator/Desktop/计划.txt";
File file = new File(URL);
if (!file.exists()) {
int i = 1 / 0;
}
InputStream inputStream = null;
OutputStream outputStream = null;
byte[] b = new byte[1024];
int len = 0;
try {
inputStream = new FileInputStream(file);
outputStream = response.getOutputStream();
response.setContentType("application/force-download");
String filename = file.getName();
response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));
response.setContentLength((int) file.length());
while ((len = inputStream.read(b)) != -1) {
outputStream.write(b, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
inputStream = null;
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.close();
outputStream = null;
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
}