参考 : 使用SpringBoot实现文件的下载 - LonZyuan - 博客园
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
@RestController
@RequestMapping("/file")
public class FileController {
@Value("${filePath:/home}")
private String filePath;
@GetMapping("/download/{fileName}")
public void download(HttpServletResponse response, @PathVariable("fileName") String fileName) {
try {
File file = new File(filePath);
String[] strings = filePath.split("/");
response.addHeader("Content-Length", String.valueOf(file.length()));
response.setHeader("content-type", fileName.split("[.]")[1]);
response.setContentType("application/octet-stream");
// 文件名中文乱码处理
response.addHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "utf-8"));
byte[] buff = new byte[1024];
//创建缓冲输入流
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
OutputStream outputStream = response.getOutputStream()) {
//这个路径为待下载文件的路径
int read = bis.read(buff);
//通过while循环写入到指定了的文件夹中
while (read != -1) {
outputStream.write(buff, 0, buff.length);
outputStream.flush();
read = bis.read(buff);
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
END。