批量上传文件
@RequestMapping({"/fileupload"})
public ResponseEntity uploadFile(HttpServletRequest request, @RequestParam("file") MultipartFile[] file) {
ResponseEntity ret = new ResponseEntity("Upload file failed!",
HttpStatus.BAD_REQUEST);
if (file == null) {
return ret;
}
try {
//创建本地文件
String folder = getUploadPath();
List<String> fileNames = new ArrayList<>();
for (int i = 0;i < file.length; i++) {
String fileName = getFileName(file[i].getOriginalFilename());
File localFile = new File(folder, fileName);
//把传上来的文件写到本地文件
file[i].transferTo(localFile);
fileNames.add(fileName);
}
//返回localFile文件名
ret = new ResponseEntity(fileNames, HttpStatus.OK);
} catch (Exception e) {
e.printStackTrace();
ret = new ResponseEntity(e.getCause(), HttpStatus.BAD_REQUEST);
}
return ret;
}
/**
* 实现功能描述:文件名后缀前添加一个时间
*/
private String getFileName(String fileName) {
String timeStr = DateUtil.getDateToString(new Date(), "yyyyMMddHHmmss");
int index = fileName.lastIndexOf(".");
fileName = fileName.substring(0, index) + "_" + timeStr + fileName.substring(index);
return fileName;
}
/**
* 实现功能描述:获取当前系统路径,jar包目录/upload
*/
private String getUploadPath() {
File path = null;
try {
path = new File(ResourceUtils.getURL("classpath:").getPath());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
if (!path.exists()) {
path = new File("");
}
File upload = new File(path.getAbsolutePath(), "upload");
if (!upload.exists()) {
upload.mkdirs();
}
return upload.getAbsolutePath();
}
public class DateUtil {
/**
* 把时间转化为指定格式字符串返回, 转化失败返回""。
*/
public static String getDateToString(Date date, String format) {
String result = "";
try {
SimpleDateFormat formater = new SimpleDateFormat(format);
result = formater.format(date);
return result;
} catch (Exception e) {
return result;
}
}
}
postMan测试结果
文件下载
@GetMapping("/fileDownload/{path}")
public void downloadFile(@PathVariable String path, HttpServletResponse response) {
try {
//拼接下载文件路径
InputStream inputStream = new FileInputStream(new File(getUploadPath(), path));
OutputStream outputStream = response.getOutputStream();
//设置内容类型为下载类型
response.setContentType("application/x-download");
response.setCharacterEncoding("UTF-8");
//设置请求头和文件下载名称,解决中文乱码问题,用postman是乱码,用浏览器是正常显示中文
response.setHeader("Content-Disposition","attachment;filename=" + URLEncoder.encode(path, "utf-8"));
IOUtils.copy(inputStream, outputStream);
outputStream.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
文件查看
@PostMapping("/queryAllFiles")
public ResponseEntity queryFiles(@RequestParam("fileNames") String fileName) throws IOException {
List<String> fileNameList = Arrays.asList(fileName.split(","));
File fileDir = ResourceUtils.getFile(getUploadPath());
if (!fileDir.exists()) {
return new ResponseEntity("文件夹路径错误:" + fileDir,
HttpStatus.BAD_REQUEST);
}
//依据入参筛选文件
File[] files = fileDir.listFiles();
List<File> fileList = new ArrayList<>();
for (File file : Objects.requireNonNull(files)) {
if (fileNameList.contains(file.getName())) {
fileList.add(file);
}
}
return ResponseEntity.ok(fileList);
}
文件删除
@PostMapping("/deleteFiles")
public ResponseEntity deleteFiles(@RequestParam("fileNames") String fileName) {
List<String> fileNameList = Arrays.asList(fileName.split(","));
boolean isDelete;
for (String name : fileNameList) {
isDelete = FileSystemUtils.deleteRecursively(new File(getUploadPath() + "/" +name));
if (!isDelete) {
return new ResponseEntity("删除文件错误:" + name,
HttpStatus.BAD_REQUEST);
}
}
return ResponseEntity.ok(true);
}