java调用接口下载文件到本地
@Value("${download.file.bom-doc-path}")
private String fieldPath;
@GetMapping("/download/web/downloadBoM")
public void downloadBoM(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
//定义变量
ResourceLoader resourceLoader = new DefaultResourceLoader();
byte[] buffer = new byte[1024];
//输出流
//设置返回文件信息
org.springframework.core.io.Resource resource = resourceLoader.getResource(fieldPath);
response.setContentType("application/vnd.ms-excel;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
String fileName = "材料清单.doc";
if (request.getHeader("user-agent").toLowerCase().contains("firefox")) {
//火狐浏览器自己会对URL进行一次URL转码所以区别处理
response.setHeader("Content-Disposition", "attachment;filename="
+ new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
} else {
response.setHeader("Content-Disposition", "attachment;filename=" +
URLEncoder.encode(fileName, StandardCharsets.UTF_8.name()));
}
try (InputStream inputStream = resource.getInputStream();
BufferedInputStream bis = new BufferedInputStream(inputStream);
OutputStream os = response.getOutputStream()) {
//将内容使用字节流写入输出流中
while (bis.read(buffer) != -1) {
os.write(buffer);
}
} catch (IOException e) {
e.printStackTrace();
}
}
download:
file:
bom-doc-path: classpath:/download/bom.doc
文件位置
此接口用于前端调用下载项目里的文件