下载文件转换成流,这里说两种流的方式:
1. 文件流
2. 字节流
一,字节流
String filePath=“/opt/peoject/file/123/pdf”; //这个是你服务上存放文件位置
方法体,代码如下:
public byte[] downLoadFile(String filePath) throws Exception {
byte[] buffer = null;
try {
File file = new File(filePath);
FileInputStream fis = new FileInputStream(filePath);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int n;
while ((n = fis.read(b)) != -1) {
bos.write(b, 0, n);
}
fis.close();
bos.close();
buffer = bos.toByteArray();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return buffer;
}
后端 controller层:
@PostMapping("/downLoadFile")
public byte[] downLoadFile(HttpServletRequest request,HttpServletResponse response){
return downLoadFile2(response,filePath);
}
前端接收处理、
参考地址:文件下载
二,文件流
public void downLoadFile2(HttpServletResponse response,String filePath) throws Exception {
File file = new File(filePath);
//获取文件名称 (例如:123.pdf)
String fileName=filePath.substring(filePath.lastIndexOf("\\"));
InputStream inputStream = new FileInputStream(file);
response.setContentType("application/pdf;charset=utf-8");
response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
IOUtils.copy(inputStream, response.getOutputStream());
response.flushBuffer();
inputStream.close();
}
后端controller
public void downLoadFile(HttpServletRequest request,HttpServletResponse response){
downLoadFile2(response,filePath);
}
下载后,浏览器这里会有显示文件