springboot+thymleaf处理多文件上传
Posted lr12339
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springboot+thymleaf处理多文件上传相关的知识,希望对你有一定的参考价值。
1thymleaf页面表单
<form method="POST" enctype="multipart/form-data" action="/moreupload">
<p>文件1:<input type="file" name="file" /></p>
<p>文件2:<input type="file" name="file" /></p>
<p>文件3:<input type="file" name="file" /></p>
<p><input type="submit" value="上传" /></p>
</form>
2写一个controller跳转到页面
@RequestMapping(value = "/moresave")
public String moresave(){
return "index2";
}
3写一个controller处理多文件上传
@RequestMapping(value="/moreupload", method= RequestMethod.POST)
@ResponseBody
public String handleFileUpload(HttpServletRequest request){
List<MultipartFile> files = ((MultipartHttpServletRequest)request).getFiles("file");
MultipartFile file = null;
BufferedOutputStream stream = null;
for (int i =0; i< files.size(); ++i) {
file = files.get(i);
if (!file.isEmpty()) {
try {
String contentType = file.getContentType();
String fileName = file.getOriginalFilename();
System.out.println("fileName-->" + fileName);
System.out.println("getContentType-->" + contentType);
String filePath = request.getSession().getServletContext().getRealPath("imgupload/");
System.out.println("filePath -->"+filePath );
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(new File(filePath + fileName)));
System.out.println("bufferedOutputStream --->>>"+bufferedOutputStream );
bufferedOutputStream.write(file.getBytes());
bufferedOutputStream.flush();
bufferedOutputStream.close();
} catch (Exception e) {
return "You failed to upload " + i + " => " + e.getMessage();
}
} else {
return "You failed to upload " + i + " because the file was empty.";
}
}
return "上传成功";
}
4展示
以上是关于springboot+thymleaf处理多文件上传的主要内容,如果未能解决你的问题,请参考以下文章
如何在 .html 文件中使用 Keycloak 将 thymleaf 与 Spring Security 一起使用?