html頁面 <form method="post" action="" enctype="multipart/form-data"> <input type="file" name="file"><br> <span class="loading"></span> <input type="submit" value="提交"> </form> controller層代碼 @GetMapping("/upload") public String upload() { return "/test"; } @PostMapping("/upload") @ResponseBody public String upload(@RequestParam("file") MultipartFile file) { /* System.out.println(username);*/ if (file.isEmpty()) { return "上傳失敗,請選擇文件"; } String fileName = file.getOriginalFilename(); String filePath = "D:/"; File dest = new File(filePath + fileName); try { file.transferTo(dest); System.out.println("上傳成功!"); return "上傳成功"; } catch (IOException e) { System.out.println("上傳失敗!"+e.toString()); } return "上傳失敗!"; } 測試:啟動項目訪問測試即可
上面是個簡單demo,下面講講springboot圖片上傳步驟
第一步:圖片上傳的絕對路徑和相對路徑都配置在yml 文件中,這樣后期項目部署到服務器上直接改yml 文件即可,免得還要找到具體的代碼再改
yml如下:名稱,存放位置都可以自定義
upload: #相對路徑 relativePath: /images/ #文件上傳路徑 profile: D:/profile/game/
第二步:讀取配置文件里的值,上傳圖片工具類如下:
package com.game.config; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Random; @Component @ConfigurationProperties(prefix = "upload")//讀取配置文件yml,以upload 開頭的屬性值 public class FileUpload { private static String profile;//絕對路徑 private static String relativePath;//相對路徑 public static String getRelativePath() { return relativePath; } public void setRelativePath(String relativePath) { this.relativePath = relativePath; } public static String getProfile() { return profile; } public void setProfile(String profile) { this.profile = profile; } //1,文件上傳后新命名規則 public static String getRandomFileName() { // 生成隨機文件名:當前年月日時分秒+五位隨機數(為了在實際項目中防止文件同名而進行的處理) // 獲取隨機數 final Random r = new Random(); int rannum = (int) (r.nextDouble() * (99999 - 10000 + 1)) + 10000; // 當前時間 long currentTimeMillis = System.currentTimeMillis(); SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss"); String nowTime =format.format(currentTimeMillis); return nowTime + rannum; } //2.存儲路徑(新放路徑是否存在) public static File getPath(){ File file=new File(FileUpload.profile);//這里是直接調用配置文件中的值 if(!file.exists()){//如果文件夾不存在 file.mkdirs();//創建文件夾 } return file; } //3.上傳圖片動作(並返回相對路徑存儲在數據庫中) public static String upload(MultipartFile file){ String str=file.getOriginalFilename();//原始圖片名稱 String lastName=str.substring(str.indexOf("."),str.length());//獲取尾綴 如.png .jpg String fileName = FileUpload.getRandomFileName();//生成的新文件名 String filePath=FileUpload.getPath().getPath();//圖片存放的硬盤位置 String relativeAdress=FileUpload.relativePath+ fileName+lastName;//相對路徑 File dest = new File(filePath +'\\'+ fileName+lastName); try { file.transferTo(dest);//上傳圖片 System.out.println("=====文件上傳成功!"); } catch (IOException e) { System.out.println("=====上傳失敗!"+e.toString()); } return relativeAdress; } }
第三步:controller層調用上傳圖片類,即可上傳如下(這里僅做參考,每個人的代碼不一樣)
@PostMapping("/goodsTypeAdd") public String addGooodsType(GoodsType goodsType,@RequestParam("file")MultipartFile file){ if (StringUtils.isNotEmpty(file.getOriginalFilename())) { goodsType.setImg(FileUpload.upload(file)); } GoodsType goodsType1=goodsTypeService.insert(goodsType); return "redirect:/admin//goodsType"; }
第四步:圖片都上傳成功了,但是怎么讓圖片在項目中顯示呢?還需要做個資源映射
package com.game.config; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class MyWebAppConfigurer implements WebMvcConfigurer { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler(FileUpload.getRelativePath()+"**").addResourceLocations("file:"+FileUpload.getProfile()); } }
我這里都是讀取yml 里的參數的,這里接個別人的圖片來說吧,
不知道總結的好不好,自己的項目是這樣弄的,謝謝大家的指點