1、配置文件
文件上传的配置如下:
# 文件上传的映射路径
upload.dir=/Users/mac/Documents/
# 单个文件的最大值,默认是1MB
spring.servlet.multipart.max-file-size=10MB
# 多个文件上传时的总大小 值,默认是10MB
spring.servlet.multipart.max-request-size=100MB
max-file-size 设置能接受的文件最大的大小,记得是MB,或KB
max-request-size 设置一次上传的所有文件的大小。
除了可以用配置文件配置还可利用java配置,如下
@Component
public class MyConfig {
@Bean
public MultipartConfigElement multipartConfigElement() {
MultipartConfigFactory factory = new MultipartConfigFactory();
//上传的单个文件最大值 KB,MB 这里设置为10MB
DataSize maxSize = DataSize.ofMegabytes(10);
DataSize requestMaxSize = DataSize.ofMegabytes(30);
factory.setMaxFileSize(maxSize);
/// 设置一次上传文件的总大小
factory.setMaxRequestSize(requestMaxSize);
return factory.createMultipartConfig();
}
}
这个方法可以放在启动类里面,也可以自己放置在一个配置类里面,让项目启动的时候能正常加载就行,这里是新建了一个配置类。
2、代码实践
单文件上传和多文件上传的html代码如下,注意,在多文件上传的input中需要加入multiple="multiple"来标识这是一个多文件上传。
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>用户文件列表页面</title>
<script th:src="@{/js/jquery.js}"></script>
<script>
$(function(){
var time;
$("#start").click(function(){
console.log("开启定时更新.........");
time = setInterval(function () {
$.get("[[@{/findAllJSON}]]", function (res) {
//遍历
$.each(res, function (index, file) {
$("#" + file.id).text(file.downcounts);
})
});
}, 3000);
});
$("#stop").click(function () {
console.log("关闭定时更新");
clearInterval(time);
});
});
</script>
</head>
<body>
<h1>欢迎: <span th:if="${session.user!=null}" th:text="${session.user.username}"/></h1>
<h3>文件列表:</h3>
<button id="start">开启定时更新</button>
<button id="stop">结束定时更新</button>
<table border="1px">
<tr>
<th>ID</th>
<th>文件原始名称</th>
<th>文件的新名称</th>
<th>文件后缀</th>
<th>存储路径</th>
<th>文件大小</th>
<th>类型</th>
<th>是否是图片</th>
<th>下载次数</th>
<th>上传时间</th>
<th>操作</th>
</tr>
<tr th:each="file,fileStat:${files}">
<td><span th:text="${file.id}"/></td>
<td><span th:text="${file.oldFileName}"/></td>
<td><span th:text="${file.newFileName}"/></td>
<td><span th:text="${file.ext}"/></td>
<td><span th:text="${file.path}"/></td>
<td><span th:text="${file.size}"/></td>
<td><span th:text="${file.type}"/></td>
<td>
<img th:if="${file.isImg}=='是'" style="width: 100px;height: 40px;" th:src="${#servletContext.contextPath}+${file.path}+'/'+${file.newFileName}" alt="">
<span th:if="${file.isImg}!='是'" th:text="${file.isImg}"/>
</td>
<td th:id="${file.id}"><span th:text="${file.downcounts}"/></td>
<td><span th:text="${#dates.format(file.uploadTime,'yyyy-MM-dd HH:mm:ss')}"/></td>
<td>
<a th:href="@{/download(id=${file.id})}">下载</a>
<a th:href="@{/download(id=${file.id},openStyle='inline')}">在线打开</a>
<a th:href="@{/delete(id=${file.id})}">删除</a>
</td>
</tr>
</table>
<hr>
<h3>上传文件:</h3>
<form th:action="@{/upload}" method="post" enctype="multipart/form-data">
<input type="file" name="inputFile">
<input type="submit" value="单文件上传">
</form>
<form th:action="@{/uploads}" method="post" enctype="multipart/form-data">
<input type="file" name="inputFiles" multiple="multiple">
<input type="submit" value="多文件上传">
</form>
</body>
</html>
它的action对应了我们controller里面访问上传文件的对应的方法的路径,method属性是post,与后端一致。type为file的input框的name属性需要与controller里面的接受对象MultipartFile 一致,如果不一致的话后端无法接受到数据。如果你已经写好后端,而前端后端参数不一致,你可以给后端参数加上一个注解。@RequestParam("inputFile") 这个注解放在MultipartFile的前面,这样即使你的参数名字不是inputFile,也能正确接受到数据。
@Controller
public class FileController {
@Autowired
private UserFileService userFileService;
@Value("${upload.dir}")
private String uploadPath;
// 返回当前用户的所有文件列表---json格式数据
@GetMapping("findAllJSON")
@ResponseBody
public List<UserFile> findAllJSON(HttpSession session, Model model) {
//在登录的session中获取用户的id
User user = (User) session.getAttribute("user");
//根据用户id查询有的文件信息
List<UserFile> userFiles = userFileService.findByUserId(user.getId());
return userFiles;
}
// 删除文件信息
@GetMapping("delete")
public String delete(String id) throws FileNotFoundException {
//根据id查询信息
UserFile userFile = userFileService.findById(id);
//删除文件
//String realPath = ResourceUtils.getURL("classpath:").getPath() + "/static" + userFile.getPath();
String realPath=uploadPath+userFile.getPath();
File file = new File(realPath, userFile.getNewFileName());
if(file.exists())file.delete();//立即删除
//删除数据库中记录
userFileService.delete(id);
return "redirect:/showAll";
}
// 文件下载,注意:attachment表示文件下载 inline表示在线打开
@GetMapping("download")
public void download(String openStyle, String id, HttpServletResponse response) throws IOException {
//获取打开方式
openStyle = openStyle == null ? "attachment" : openStyle;
//获取文件信息
UserFile userFile = userFileService.findById(id);
//点击下载链接更新下载次数
if ("attachment".equals(openStyle)) {
userFile.setDowncounts(userFile.getDowncounts() + 1);
userFileService.update(userFile);
}
//根据文件信息中文件名字 和 文件存储路径获取文件输入流
//String realpath = ResourceUtils.getURL("classpath:").getPath() + "/static" + userFile.getPath();
String realpath=uploadPath+userFile.getPath();
//获取文件输入流
FileInputStream is = new FileInputStream(new File(realpath, userFile.getNewFileName()));
//附件下载
response.setHeader("content-disposition", openStyle + ";fileName=" + URLEncoder.encode(userFile.getOldFileName(), "UTF-8"));
//获取响应输出流
ServletOutputStream os = response.getOutputStream();
//文件拷贝
IOUtils.copy(is, os);
IOUtils.closeQuietly(is);
IOUtils.closeQuietly(os);
}
// 单文件上传
@PostMapping("upload")
public String upload(@RequestParam("inputFile")MultipartFile aaa, HttpSession session) throws IOException {
if (aaa.getSize()<=0){
return "redirect:/showAll";
}
//获取上传文件用户id
User user = (User) session.getAttribute("user");
//获取文件原始名称
String oldFileName = aaa.getOriginalFilename();
//获取文件后缀
String extension = "." + FilenameUtils.getExtension(aaa.getOriginalFilename());
//生成新的文件名称
String newFileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + UUID.randomUUID().toString().replace("-", "") + extension;
//文件大小
Long size = aaa.getSize();
//文件类型
String type = aaa.getContentType();
//处理根据日期生成目录
//String realPath = ResourceUtils.getURL("classpath:").getPath() + "/static/files";
String dateFormat = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
String dateDirPath = uploadPath + "/file/" + dateFormat;
File dateDir = new File(dateDirPath);
if (!dateDir.exists()) dateDir.mkdirs();
//处理文件上传
aaa.transferTo(new File(dateDir, newFileName));
//将文件信息放入数据库保存
UserFile userFile = new UserFile();
userFile.setOldFileName(oldFileName).setNewFileName(newFileName).setExt(extension).setSize(String.valueOf(size))
.setType(type).setPath("/file/" + dateFormat).setUserId(user.getId());
userFileService.save(userFile);
return "redirect:/showAll";
}
//多文件上传
@PostMapping("uploads")
public String uploads(MultipartFile[] inputFiles, HttpSession session) throws IOException {
User user = (User) session.getAttribute("user");
for (MultipartFile inputFile : inputFiles) {
addFile(inputFile,user);
}
return "redirect:/showAll";
}
//上传函数
public void addFile(MultipartFile file,User user) throws IOException {
if(file.getSize()<=0){
return ;
}
//获取文件原始名称
String oldFileName = file.getOriginalFilename();
//获取文件后缀
String extension = "." + FilenameUtils.getExtension(file.getOriginalFilename());
//生成新的文件名称
String newFileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + UUID.randomUUID().toString().replace("-", "") + extension;
//文件大小
Long size = file.getSize();
//文件类型
String type = file.getContentType();
//处理根据日期生成目录
//String realPath = ResourceUtils.getURL("classpath:").getPath() + "/static/files";
String dateFormat = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
String dateDirPath = uploadPath + "/file/" + dateFormat;
File dateDir = new File(dateDirPath);
if (!dateDir.exists()) dateDir.mkdirs();
//处理文件上传
file.transferTo(new File(dateDir, newFileName));
//将文件信息放入数据库保存
UserFile userFile = new UserFile();
userFile.setOldFileName(oldFileName).setNewFileName(newFileName).setExt(extension).setSize(String.valueOf(size))
.setType(type).setPath("/file/" + dateFormat).setUserId(user.getId());
userFileService.save(userFile);
}
// 展示所有文件信息
@GetMapping("/showAll")
public String findAll(HttpSession session, Model model) {
//在登录的session中获取用户的id
User user = (User) session.getAttribute("user");
//根据用户id查询有的文件信息
List<UserFile> userFiles = userFileService.findByUserId(user.getId());
//存入作用域中
model.addAttribute("files", userFiles);
return "showAll";
}
}
3、效果展示
添加图片之后效果如下:
以上就是所有内容,有问题的小伙伴欢迎私信或留言。
全部评论