前端
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>文件上传和下载</title>
</head>
<body>
<form action='/file/upload' method='post' enctype='multipart/form-data'>
<input type='file' name='file'>
<button type='submit'>上传</button>
</form>
</body>
</html>
java controller层
package com.zhou.controller;
import org.apache.commons.io.FilenameUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
@RestController
@RequestMapping("/file")
public class TiktokSecuidController1 {
@RequestMapping(value = "/upload", method = RequestMethod.POST, produces = "text/html;charset=utf-8")
@ResponseBody
public String fileupload(@RequestParam(value = "file", required = false) MultipartFile file) throws IOException {
String oldName = file.getOriginalFilename();
//获取原始文件的后缀
String extension = "." + FilenameUtils.getExtension(oldName);
//生成新的文件名称
String newFileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + UUID.randomUUID().toString().replace("-", "") + extension;
//文件大小
Long size = file.getSize();
//文件的类型
String fileType = file.getContentType();
//生成日期格式的目录 接收到的文件放在static下面的files中
String realpath = ResourceUtils.getURL("classpath:").getPath() + "static/files";
//在files中动态的创建文件夹
String dateDirpath = realpath + "/" + new SimpleDateFormat("yyyy-MM-dd").format(new Date());
File datedir = new File(dateDirpath);
if (!datedir.exists()) {
datedir.mkdirs();
}
//处理文件上传
System.out.println(datedir);
file.transferTo(new File(datedir, newFileName));
return "success";
}
}
pom
<!-- 文件上传下载工具包 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>