环境准备
自己创建要给springboot项目,导入基本的环境, 准备一份upload.html用于上传 准备一份download.html用于下载 upload.html代码如下:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form th:action="@{/file/upload}" method="post" enctype="multipart/form-data">
<input type="file" name="upload"><br>
<input type="submit" value="上传文件">
</form>
</body>
</html>
download.html代码如下:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!--文件下载-->
<p>
<a th:href="@{/file/download(fileName=头像73b4cd2181c9447393bd6b8908ea57ba.jpg)}">下载照片</a>
<a th:href="@{/file/download(fileName=mysql8.0.16配置ac8336e2a17d441398a153336638ea44.docx)}">下载world文件</a>
</p>
</body>
</html>
文件上传代码和下载代码如下:
@Controller
@RequestMapping("/file")
public class FileController {
@GetMapping("/goUpload")
public String goUpload() {
return "upload";
}
@GetMapping("/goDownload")
public String goDownload() {
return "download";
}
@ResponseBody
@RequestMapping("/upload")
public String upload(MultipartFile upload) throws IOException {
String originalFilename = upload.getOriginalFilename();
String fileOgrName = originalFilename.substring(0, originalFilename.lastIndexOf("."));
String extension = "." + FilenameUtils.getExtension(originalFilename);
String newFileName = fileOgrName + UUID.randomUUID().toString().replace("-", "") + extension;
String realPath = ResourceUtils.getURL("classpath:").getPath() + "static/files";
String dateDirPath = realPath + "/";
System.out.println(dateDirPath);
File dateFile = new File(dateDirPath);
if (!dateFile.exists()){
dateFile.mkdirs();
}
upload.transferTo(new File(dateDirPath,newFileName));
return "文件上传成功";
}
@ResponseBody
@RequestMapping("/download")
public String download(String fileName, HttpServletRequest request, HttpServletResponse response) throws IOException {
String realPath = ResourceUtils.getURL("classpath:").getPath() + "static/files";
FileInputStream fileInputStream = new FileInputStream(new File(realPath, fileName));
response.setHeader("content-disposition","attachment;filename="+ URLEncoder.encode(fileName,"utf-8"));
ServletOutputStream outputStream = response.getOutputStream();
IOUtils.copy(fileInputStream, outputStream);
IOUtils.closeQuietly(fileInputStream);
IOUtils.closeQuietly(outputStream);
return "文件下载成功";
}
}
注意
我们这里没有使用数据库存上传的文件信息,在实际开发中我们会建立一个数据库表,用于存储上传文件的信息 主要存储以下信息:
- 文件原始文件名称===(可以在下载的时候使用,下载的时候使用源文件名字)
- 文件的新的文件名称===(上传到服务器上防止重复,一般使用时间戳+uuid)
- 文件后缀
- 文件存储路径===(方便查找,一般我们都是日期目录存储)
- 文件大小
- 文件类型
- 上传时间
等等,更具业务需求添加。
|