HttpServletResponse response下载
public void downLoadFile(String path,HttpServletResponse response) throws IOException {
//下载的文件名称,带后缀
String fileName=path.substring(path.lastIndexOf(File.separatorChar) + 1);
response.reset();
response.setContentType("application/octet-stream");//以流形式下载
response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));//设置文件名称
OutputStream out = response.getOutputStream();
BufferedInputStream br = new BufferedInputStream(new FileInputStream(new File(path)));
byte[] buf = new byte[1024];
int len = 0;
while ((len = br.read(buf)) > 0)
out.write(buf, 0, len);
br.close();
out.close();
}
ResponseEntity下载
下载接口
传递参数为要下载的文件的名字,然后拼接文件存放服务器的地址,把地址和文件名传递给文件下载方法。
@GetMapping("/{param}/downloadFile")
public ResponseEntity<Resource> downloadFile(@PathVariable String param) {
String downloadURl = uploadUrl + "/dev" + File.separator + param;
return beginDownFile(downloadURl, param);
}
文件下载方法
import org.springframework.core.io.Resource;
import org.springframework.http.ResponseEntity;
/**
* 执行文件下载
*
* @param param
* @return
*/
public ResponseEntity<Resource> beginDownFile(String downloadUrl, String param) {
File file = new File(downloadUrl);
Path path = Paths.get(file.getAbsolutePath());
ByteArrayResource resource = null;
try {
resource = new ByteArrayResource(Files.readAllBytes(path));
} catch (IOException e) {
e.printStackTrace();
}
return ResponseEntity.ok().header("Content-Disposition", "attachment;filename=" + param)
.contentLength(file.length()).contentType(MediaType.parseMediaType("application/octet-stream"))
.body(resource);
}
File.separator
简介
File.separator 的作用相当于 ’ \ ’
在 windows 中 文件文件分隔符 用 ’ \ ’ 或者 ’ / ’ 都可以
但是在 Linux 中,是不识别 ’ \ ’ 的,而 File.separator 是系统默认的文件分隔符号,在 UNIX 系统上,此字段的值为 ’ / ’
在 Microsoft Windows 系统上,它为 ’ \ ’ 屏蔽了这些系统的区别。
所以用 File.separator 保证了在任何系统下不会出错。
拓展
File 类还有:
1、separatorChar
与系统有关的默认名称分隔符,为了方便,它被表示为一个字符串。此字符串只包含一个字符
2、pathSeparatorChar
与系统有关的路径分隔符,为了方便,它被表示为一个字符串
3、pathSeparator
此字符用于分隔以路径列表形式给定的文件序列中的文件名
在 UNIX 系统上此字段为 ’ : ’
在 Microsoft Windows 系统上,它为 ’ ;’