springBoot-------實現簡單的檔案上傳
阿新 • • 發佈:2021-01-07
引言
web開發中,檔案上傳是必不可少的。在springboot開發中,檔案上傳很是簡單,sb為我們寫好了檔案上傳工具MultipartFile
。即用MultipartFile
來接收檔案,只需幾行程式碼即可實現
內容
檔案上傳有單檔案和多檔案,多檔案是在單檔案的基礎上新增multiple屬性,即看下面程式碼(從頁面抽取的一部分程式碼)
<div class="form-group"> <!--單檔案--> <label for="headImage">選擇頭像</label> <input type="file" id="headImage" name="headImage"> <p class="help-block">Example block-level help text here.</p> </div> <!--多檔案--> <div class="form-group"> <label for="photos">生活照</label> <input type="file" id="photos" name="photos" multiple> <p class="help-block">Example block-level help text here.</p> </div>
在controller獲取檔案時候,需要對檔案進行判斷操作。
+ 單檔案判斷是否為空 呼叫isEmpty()方法
+ 多檔案判斷長度是否大於0,獲得單個檔案後,繼續判斷是否為空
form表單:我用的是thymeleaf風格:method="post" enctype="multipart/form-data
固定寫死
<form role="form" th:action="@{/load_files}" method="post" enctype="multipart/form-data"> <div class="form-group"> <label for="exampleInputEmail1">電子郵件</label> <input type="email" name="email" class="form-control" id="exampleInputEmail1" placeholder="Enter email"> </div> <div class="form-group"> <label for="exampleInputPassword1">姓名</label> <input type="text" name="username" class="form-control" id="exampleInputPassword1" placeholder="Password"> </div> <div class="form-group"> <label for="headImage">選擇頭像</label> <input type="file" id="headImage" name="headImage"> <p class="help-block">Example block-level help text here.</p> </div> <div class="form-group"> <label for="photos">生活照</label> <input type="file" id="photos" name="photos" multiple> <p class="help-block">Example block-level help text here.</p> </div> <div class="checkbox"> <label> <input type="checkbox"> Check me out </label> </div> <button type="submit" class="btn btn-primary">Submit</button> </form>
Controller:上傳檔案
@SneakyThrows @PostMapping("/load_files") public String load(@RequestParam("email") String email, @RequestParam("username") String username, @RequestPart("headImage") MultipartFile headImg, @RequestPart("photos") MultipartFile[] photos){ if (!headImg.isEmpty()){ // 獲取檔名字 String name = headImg.getOriginalFilename(); // 不為空,儲存 路徑必須存在,不存在會報錯 headImg.transferTo(new File("e://cache//"+name)); } if (photos.length > 0){ for (MultipartFile photo : photos) { if (photo.isEmpty()){ continue; } String name = photo.getOriginalFilename(); photo.transferTo(new File("e://cache//photos//"+name)); } } log.info("上傳成功"); return "main"; }
結果
再說一句
可能有的人會報圖片太大的錯誤。springBoot預設上傳單個檔案的大小是1MB,多個檔案大小是10MB(多個檔案上傳的時,單個檔案不能超過1MB)
解決方案:設定大小
spring:
servlet:
multipart:
max-file-size: 10MB #單個檔案大小
max-request-size: 100MB #所有檔案大小