@GetMapping("downloadImg")
public ResponseEntity<byte[]> downloadImg(HttpServletRequest request) {
String realPath = request.getServletContext().getRealPath("upload/2.jpg");
byte[] bytes;
try {
FileInputStream fileInputStream = new FileInputStream(realPath);
bytes = new byte[fileInputStream.available()];
int read = fileInputStream.read(bytes);
} catch (IOException e) {
throw new RuntimeException(e);
}
//告知浏览器,我的流是一个 附件 (文件),浏览器触发下载
HttpHeaders httpHeaders = new HttpHeaders();
String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1);
System.out.println(fileName);
httpHeaders.setContentDispositionFormData("attachment", fileName);
//返回对象
ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, httpHeaders, HttpStatus.OK);
return responseEntity;
}
乱码解决:获取文件名的时候,将文件名转为utf-8格式:
String encode = URLEncoder.encode(fileName, "UTF-8");
下载rar文件如下:
@GetMapping("downLoadTxt")
public ResponseEntity<byte[]> downLoadTxt(HttpServletRequest request){
//获取要下载的文件地址
String realPath = request.getServletContext().getRealPath("upload/新建文本文档.txt");
byte[] bytes;
String fileName;
try {
//将文件转为字节流对象
FileInputStream fileInputStream = new FileInputStream(realPath);
//定义接收字节流对象的数组
bytes = new byte[fileInputStream.available()];
//读取字节流
int read = fileInputStream.read(bytes);
//获取文件名并且将文件名编码格式改为utf-8
fileName = URLEncoder.encode(realPath.substring(realPath.lastIndexOf("\\")+1),"UTF-8");
} catch (IOException e) {
throw new RuntimeException(e);
}
//告诉浏览器,出发下载
HttpHeaders httpHeaders = new HttpHeaders();
//设置浏览器下载附件,传入文件名
httpHeaders.setContentDispositionFormData("attachment",fileName);
//返回响应实体,字节流数组,下载附件,状态
return new ResponseEntity<byte[]>(bytes,httpHeaders,HttpStatus.OK);
}
标签:realPath,文件,spring,bytes,fileName,fileInputStream,new,httpHeaders,下载
From: https://www.cnblogs.com/Liku-java/p/17184206.html