一、读取
public String setFileName() {
StringBuilder strFile = new StringBuilder();
String filePath = "你的路径";
File directory = new File(filePath);
// 确保路径确实指向一个目录
if (directory.exists() && directory.isDirectory()) {
// 获取目录下的所有文件和子目录
File[] files = directory.listFiles();
if (files != null) {
for (File file1 : files) {
strFile.append(file1.getName()+",");
}
} else {
logger.error("该目录下没有文件或子目录");
}
} else {
logger.error("路径不是一个有效的目录或者不存在");
}
return strFile.toString();
}
二、查看
1、
@RequestMapping(value = "/view/{filename}", method = RequestMethod.GET)
public void downloadReadOnlyFile(@PathVariable String filename,
HttpServletResponse response) throws Exception {
File file = new File(filePath + fileName);
file.setReadOnly();//只读
if (!file.exists()) {
throw new FileNotFoundException(filename);
}
// 设置响应头 动态设置Content-Type
Path filePathOne = Paths.get(filePath, filename);
MediaType mediaType = MediaType.valueOf(Files.probeContentType(filePathOne));
response.setContentType(String.valueOf(mediaType));
response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\"");//inline浏览器打开,attachment下载
response.setHeader("Content-Transfer-Encoding", "binary");
response.setHeader("Pragma", "no-cache");
response.setHeader("Expires", "0");
try {
FileInputStream inputStream = new FileInputStream(file);// 打开文件输入流
ServletOutputStream outputStream = response.getOutputStream();// 获取输出流
// 复制文件内容到响应输出流
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
// 关闭流
outputStream.flush();
outputStream.close();
inputStream.close();
} catch (IOException e) {
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
// 可以记录日志或者进行其他错误处理
}
}
2、
@RequestMapping(value = "/view/{type}/{filename}", method = RequestMethod.GET)
public ResponseEntity<FileSystemResource> viewFile(@PathVariable String filename, @PathVariable String type) throws IOException {
String filePath = "D:/";
Path filePathOne = Paths.get(filePath, filename+"."+type);
FileSystemResource file = new FileSystemResource(filePathOne.toString());
if (!file.exists()) {
return new ResponseEntity<FileSystemResource>(HttpStatus.NOT_FOUND);
}
// 动态设置Content-Type
MediaType mediaType = MediaType.valueOf(Files.probeContentType(filePathOne));
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + file.getFilename() + "\"")
.contentType(mediaType) // 或者根据文件类型动态设置
.body(file);
}