實現文件上傳和回顯
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