上传 前端代码
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/web/thymeleaf/layout"
layout:decorator="layout">
<head>
<meta charset="UTF-8" />
<title>Title</title>
<script type="text/javascript" src="../static/jquery-3.2.1.min.js" th:src="jquery-3.2.1.min.js" ></script>
</head>
<body>
<form action="upload" method="post" enctype="multipart/form-data" >
<input type="file" name="file" >
<button type="submit">提交</button>
</form>
</body>
</html>
上传 后端代码
/**
* 文件上传 单个
* @param file
* @return
*/
@PostMapping("/upload")
@ResponseBody
public String upload(@RequestParam MultipartFile file) {
if (file.isEmpty()) {
return "The file is null";
}
String fileName = file.getOriginalFilename();
String fileSuffix = fileName.substring(fileName.lastIndexOf("."));
String filePath = "D://testUpload//img//";
File dest = new File(filePath + fileName);
boolean flag = false;
if (!dest.getParentFile().exists()) {
flag = dest.getParentFile().mkdirs();
}
try {
file.transferTo(dest);
String path = dest.getPath();
return "Upload success";
} catch (IOException e) {
e.printStackTrace();
return "Upload fail";
}
}
File的mkdir创建当前文件,mkdirs 创建当前文件及不存在的父级文件
下载 后端代码
/**
* 下载
* @return
* @throws IOException
*/
@GetMapping("/media")
public ResponseEntity<InputStreamResource> downloadFile(@RequestParam String url)
throws IOException {
String filePath = "D:/testUpload/img/"+url;
FileSystemResource file = new FileSystemResource(filePath);
String name = file.getFilename();
if(!file.exists()){
return null;
}
HttpHeaders headers = new HttpHeaders();
headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
headers.add("Content-Disposition","attachment; fileName="+new String(name.getBytes("utf-8"),"ISO-8859-1"));
headers.add("Pragma", "no-cache");
headers.add("Expires", "0");
return ResponseEntity
.ok()
.headers(headers)
.contentLength(file.contentLength())
.contentType(MediaType.parseMediaType("application/x-msdownload"))
.body(new InputStreamResource(file.getInputStream()));
}
删除 后端代码
/**
* 删除文件
* @param url
* @return
*/
@GetMapping("/deleteFile")
@ResponseBody
public String deleteFile(@RequestParam String url){
File file = new File("D:/testUpload/img/"+url);
if(!file.exists()){
return "文件不存在";
}
if(file.isFile()){
boolean flag = file.delete();
if(flag){
return "删除成功";
}else {
return "删除失败";
}
}
else {
return "这不是个文件 无法删除";
}
}