虚拟目录配置
....
file:
#文件静态资源访问目录
static-access-path: /fileManager/uploads
@Value("${file.save-path-unix}")
private String rootPathUnix;
@Value("${file.save-path-windows}")
private String rootPathWindows;
@Value("${file.static-access-path}")
private String fileAccessPath;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
String os = System.getProperty("os.name").toLowerCase();
String path = os.contains("windows") ? rootPathWindows : rootPathUnix;
registry.addResourceHandler(fileAccessPath).addResourceLocations("file:" + path);
}
}
文件下载
文件下载,访问虚拟目录是可以的。 如果要实现浏览器强制下载(修改响应头),代码如下
@GetMapping("/forceDownload")
public MVCResult forceDownload(@RequestParam(value = "fileName", defaultValue = "") String fileName,
@RequestParam(value = "outPutName", required = false) String outPutName,
HttpServletResponse response) throws UnsupportedEncodingException {
if (StringUtils.isEmpty(fileName)) {
return MVCResult.fail("forceDownload", "文件名缺失");
}
String sys = System.getProperty("os.name").toLowerCase();
String path = sys.contains("windows") ? rootPathWindows : rootPathUnix;
String filePath = path + fileName;
File file = new File(filePath);
if (!file.exists()) {
return MVCResult.fail("forceDownload", "文件不存在");
}
String orgName = StringUtils.isEmpty(outPutName) ? fileName : outPutName;
String newFileName = new String(orgName.getBytes(),"ISO8859-1");;
response.setHeader("Content-Disposition", "attachment;filename=" + newFileName);
byte[] buff = new byte[1024];
BufferedInputStream bis = null;
OutputStream os = null;
try {
os = response.getOutputStream();
bis = new BufferedInputStream(new FileInputStream(file));
int i = bis.read(buff);
while (i != -1) {
os.write(buff, 0, buff.length);
os.flush();
i = bis.read(buff);
}
int m = i / 0;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return MVCResult.succ("forceDownload", fileName);
}
String newFileName = new String(orgName.getBytes(),"ISO8859-1");
使下载下来的文件名不是乱码。