javaEE --springboot #实现图片上传和回显 #单文件上传 #多文件上传 #ajax异步文件上传 (非常详细,从创建项目开始)
实现文件上传和回显
1、新建一个SpringBoot项目,选择 Spring Web 和 thymeleaf 依赖 。pow.xml文件下的依赖如下
2、根据下图,创建如下文件
3、直接上代码
配置文件 application.xml
server:
port: 8005
file:
upload:
path: F://upload/
relationImg: /images/
配置类 MyWenMvcConfigurer.java
/** 资源映射路径 */ @Configuration public class MyWebMvcConfigurer implements WebMvcConfigurer { /** 保存的真实地址 */ @Value("${file.upload.path}") String sysPath; /** 请求的相对地址 */ @Value("${file.upload.relationImg}") String relationImg; @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { /** 将相对地址映射到真实地址 */ registry.addResourceHandler(relationImg+"**").addResourceLocations("file:/"+sysPath+relationImg); } }
服务层接口 UploadService.java
public interface UploadService { /** 保存文件并返回文件的相对路径 */ public String uploadImg(MultipartFile file); }
服务层实现类 UploadServiceImpl.java
@Service public class UploadServiceImpl implements UploadService { @Value("${file.upload.path}") String sysPath; @Value("${file.upload.relationImg}") String relationImg; @Override public String uploadImg(MultipartFile file) { //uuid生成的唯一前缀 + 上传文件名 构成唯一的新文件名 String fileName= UUID.randomUUID()+"_"+file.getOriginalFilename(); //文件保存路径 String path=sysPath+relationImg; //新建文件filepath File filepath=new File(path,fileName); //判断路径是否存在,如果不存在就创建一个 if(!filepath.getParentFile().exists()){ filepath.getParentFile().mkdirs(); } try { //将上传的文件file写入文件filepath file.transferTo(new File(path+File.separator+fileName)); }catch (IOException e){ e.printStackTrace(); } //将请求文件的相对路径返回 return relationImg+fileName; } }
控制类 UploadController.java
@Controller public class UploadController { @Autowired UploadService uploadService; @GetMapping("/uploadImg") public String getuploadImg(){ return "/upload/uploadImg"; } @PostMapping("/uploadImg") public String uploadImg(@RequestParam("file")MultipartFile file, Model model){ String imgUrl=uploadService.uploadImg(file); model.addAttribute("imgUrl",imgUrl); return "/upload/uploadImg"; } }
视图层 uploadImg.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>图片上传并回显</title>
</head>
<body>
<form action="/uploadImg" enctype="multipart/form-data" method="post">
<input type="file" accept="image/*" name="file">
<input type="submit" value="上传" style="background-color: antiquewhite">
</form>
图片地址:[[${imgUrl}]]
<br>
<img th:src="@{${imgUrl}}" style="width: 200px;height: 200px;border-radius: 20px;">
</body>
</html>
效果图:
真实保存路径:F:\upload\images
注意下面两张图的名字,第一张多了的前缀就是 UUID.randomUUID() 生成的,为了保证文件名的唯一性
单文件上传
控制层 FileController.java
@Controller public class FileController { //单文件上传页面跳转 @GetMapping("/singleUpload") public String singleUpload(){ return "singleUpload"; } //单文件上传管理 @PostMapping("/singleUploadFile") public String singleUploadFile(HttpServletRequest httpServletRequest, MultipartFile file, Model model) throws IOException { //获取文件名以及后缀名 String fileName=file.getOriginalFilename(); //重新生成文件名(根据具体情况生成对应文件名) fileName= UUID.randomUUID()+"_"+fileName; //指定上传文件本地存储目录,不存在需要提前创建 String dirPath="F:/file/"; File filePath=new File(dirPath); //指定上传文件本地存储目录,不存在需要提前创建 if(!filePath.exists()){ filePath.mkdirs(); } try{ //将文件写入磁盘 file.transferTo(new File(dirPath,fileName)); model.addAttribute("uploadStatus","上传成功"); }catch (Exception e){ e.printStackTrace(); model.addAttribute("uploadStatus","上传失败:"+e.getMessage()); } //将带上传状态信息回调到文件上传页面 return "singleUpload"; } }
singleUpload.html
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> <title>单文件上传</title> <link th:href="@{/css/bootstrap.min.css}"rel="stylesheet"> <script th:src="@{/js/jquery/min.js}"></script> </head> <body> <div th:if="${uploadStatus}" style="color:red;font-size: large" th:text="${uploadStatus}">上传成功!</div> <form th:action="@{/singleUploadFile}" method="post" enctype="multipart/form-data"> <div class="form-group"> <label>单文件上传</label> <input class="form-control-file" type="file" name="file" required="required"> </div> <input id="submit" type="submit" value="上传"> </form> </body> </html>
效果图:
点击上传后
保存地址
多文件上传
控制层 FileController.java
@Controller public class FileController { //多文件上传页面跳转 @GetMapping("/mutiUpload") public String mutiUpload(){ return "mutiUpload";} //多文件上传管理 @PostMapping("/mutiUploadFile") public String mutiUploadFiles(MultipartFile[] files,Model model){ for(MultipartFile file:files){ String fileName=file.getOriginalFilename(); fileName=UUID.randomUUID()+"_"+fileName; String dirPath="F:/file/"; File filePath=new File(dirPath); if(!filePath.exists()){ filePath.mkdirs(); } try{ file.transferTo(new File(dirPath+fileName)); model.addAttribute("uploadStatus","上传成功"); } catch (IOException e) { e.printStackTrace(); model.addAttribute("uploadStatus","上传失败"); } } return "mutiUpload"; } }
mutiUpload.html
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> <title>动态添加文件上传列表</title> <link th:href="@{/css/bootstrap.min.css}"rel="stylesheet"> <script th:src="@{/js/jquery-3.5.1.min.js}"></script> </head> <body> <div th:if="${uploadStatus}" style="color:red;" th:text="${uploadStatus}">上传成功</div> <form th:action="@{/mutiUploadFile}" method="post" enctype="multipart/form-data"> <div class="form-group"> <label>动态添加文件上传</label> <input type="button" value="添加文件" onclick="add()"/> <div id="file" class="" th:value="文件上传区域"></div> </div> <input id="submit" type="submit" value="上传" style="display: none;margin-top:10px;"> </form> <script> //动态添加上传按钮 function add() { var innerdir="<div>"+ "<input type='file' style='margin:5px;' name='files' required='required'>"+ "<input type='button' value='删除' onclick='remove(this)'>"+ "</div>" $("#file").append(innerdir); $("#submit").css("display","block"); } function remove(obj) { $(obj).parent().remove(); if($("#file div").length==0){ $("#submit").css("display","none"); } } </script> </body> </html>
效果图:
点击上传后:
保存的地址:
Ajax异步文件上传
控制层
@Controller public class FileController { //ajax文件上传页面跳转 @GetMapping("/ajaxUpload") public String ajaxUpload(){return "ajaxUpload";} //ajax文件上传管理 @ResponseBody @PostMapping("/ajaxUploadFile") public Map ajaxUploadFile(MultipartFile[] files){ Map<String,Object> map=new HashMap<>(); map.put("test","test"); for(MultipartFile file:files){ String fileName=file.getOriginalFilename(); fileName=UUID.randomUUID()+"_"+fileName; String dirPath="F:/file/"; File filePath=new File(dirPath); if(!filePath.exists()){ filePath.mkdirs(); } try{ file.transferTo(new File(dirPath+fileName)); map.put("msg","上传成功"); } catch (Exception e) { e.printStackTrace(); map.put("msg","上传失败"); } } return map; } }
视图层
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> <title>异步无刷文件上传</title> <link th:href="@{/css/bootstrap.min.css}"rel="stylesheet"> <script th:src="@{/js/jquery-3.5.1.min.js}"></script> </head> <body> <form id="form"> <div class="form-group"> <label>异步无刷文件上传</label> <input type="button" value="添加文件" onclick="add()"/> <div id="file" class="" th:value="文件上传区域"></div> </div> <input id="submit" type="button" value="上传" onclick="ajaxUpload()" style="display: none;margin-top:10px;"> </form> <script> function ajaxUpload() { var form=new FormData(); //获取选择的文件 $.each($('input[name="files"]'),function(index,item){ form.append("files",item.files[0]) }); $.ajax({ method: 'post', url: '/ajaxUploadFile', data: form, processData: false, contentType: false, success: function (res) { alert(res.msg); }, error: function () { console.log("ajax请求失败"); } }); } //动态添加上传按钮 function add() { var innerdir="<div>"+ "<input type='file' style='margin:5px;' name='files' required='required'>"+ "<input type='button' value='删除' onclick='remove(this)'>"+ "</div>" $("#file").append(innerdir); $("#submit").css("display","block"); } function remove(obj) { $(obj).parent().remove(); if($("#file div").length==0){ $("#submit").css("display","none"); } } </script> </body> </html>
效果图:
保存地址
参考博客网址:https://www.cnblogs.com/zhainan-blog/p/11169163.html(springboot\thymeleaf实现图片上传和回显)
参考:JavaEE实验9(单文件上传\多文件上传\ajax异步文件上传)
文档:
链接:https://pan.baidu.com/s/1zb9UsQz_uXU5b_BAOQr6PQ
提取码:9eim
源码:
链接:https://pan.baidu.com/s/1Tvw7y0PwLylBGDUPLu--ww
提取码:09u1