Springboot?上傳文件或頭像(MultipartFile、transferTo)
1. 在配置文件中指定外部環(huán)境, 注入到代碼中
頭像上傳路徑, 若不存在, 會(huì)根據(jù)該路徑創(chuàng)建指定路徑文件夾
upload: path: D:\\upload\headImgs
創(chuàng)建類 FileUtils 并讀取配置文件中的值
@Component @ConfigurationProperties(prefix = "upload") @Data public class FileUtils { private String path; public File getPath() { // 構(gòu)建上傳文件的存放 "文件夾" 路徑 String fileDirPath = new String(path); File fileDir = new File(fileDirPath); if (!fileDir.exists()) { // 遞歸生成文件夾 fileDir.mkdirs(); } return fileDir; } public boolean del(String filename) { File file = new File(path + File.separator + filename); return file.delete(); } public boolean del(String path, String filename) { return new File(path + File.separator + filename).delete(); } }
2. 設(shè)置上傳文件的限制配置
spring: servlet: multipart: max-request-size: 10MB # 上傳文件的最大值 max-file-size: 5MB # 單個(gè)文件上傳的最大值
3. 設(shè)置外部路徑映射到url
創(chuàng)建config類
注意: 映射路徑時(shí), 最后面一定要加 / (File.separator)
@Configuration public class WebMvcConfig extends WebMvcConfigurationSupport { @Autowired private FileUtils fileUtils; @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { // 加入頭像文件夾映射 可通過 localhost:7188/headimage/.... 訪問到指定位置的圖片 registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/"); // 默認(rèn)頭像 registry.addResourceHandler("/headimage/**").addResourceLocations("file:"+fileUtils.getPath().getPath()+ File.separator); super.addResourceHandlers(registry); } }
注意:
- 此時(shí)映射了兩個(gè)路徑
- 外部環(huán)境的路徑static目錄下的路徑(該路徑用于存放一張默認(rèn)圖片隨意一張, 作為默認(rèn)頭像 可命名為 default.jpg)
4. 用戶實(shí)體類中 加入 image 字段
該字段默認(rèn)值為 ‘static/default.jpg’ 即為用戶的默認(rèn)頭像
作用: 存放圖片的相對(duì)路徑
5. Controller層編寫
@RestController @RequestMapping("operate/User") public class UserController extends BaseController<UserService> { @ApiOperation("修改(可以修改頭像和郵箱)") @PutMapping public R modify(MultipartFile headImg, String email){ return baseService.modify(headImg, email); } }
6. Service層編寫
public interface UserService extends IService<User> { R modify(MultipartFile headImg, String email); } @Slf4j @Service public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserService { @Autowired private FileUtils fileUtils; /** * 獲取當(dāng)前用戶名 * * @return */ private String getCurrentuserName() { // ... return username; } /** * 獲取當(dāng)前用戶 * * @return */ public User getCurrentuser() { // ... return user; } @Override public R modify(MultipartFile headImg, String email) { // 校驗(yàn)圖片格式 if (!imageTypeRight(headImg)) return R.fail("圖片格式不正確"); // 獲取上傳文件后的路徑 String path = uploadFile(headImg); User currentuser = getCurrentuser(); // 刪除之前的頭像(如果是默認(rèn)頭像不刪除) String image = currentuser.getImage(); if (!image.equals("static/default.png")) { if (!fileUtils.del(image.substring(path.indexOf("/") + 1))) { log.info("修改頭像時(shí), 原來的頭像刪除失敗"); } else { log.info("修改頭像時(shí), 原來的頭像刪除成功"); } } // 修改數(shù)據(jù)庫(kù)中頭像的路徑信息 和 郵箱 update(Wrappers.<User>lambdaUpdate() .set(User::getEmail, email) .set(User::getImage, path) .eq(User::getUsername, currentuser.getUsername())); // 該路徑為圖片相對(duì)路徑 可放在url中的服務(wù)后面 進(jìn)行訪問 // 比如: http://localhost:9000/cloudos-opt/headimage/01c8806dc26d45539b53c22c766cd250.jpg // http://localhost:9000/cloudos-opt/static/default.png return R.success(null, path); } /** * 驗(yàn)證圖片的格式 * * @param file 圖片 * @return */ private boolean imageTypeRight(MultipartFile file) { // 首先校驗(yàn)圖片格式 List<String> imageType = Lists.newArrayList("jpg", "jpeg", "png", "bmp", "gif"); // 獲取文件名,帶后綴 String originalFilename = file.getOriginalFilename(); // 獲取文件的后綴格式 String fileSuffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1).toLowerCase(); //不帶 . if (!imageType.contains(fileSuffix)) return false; return true; } /** * 上傳文件 * * @param file * @return 返回路徑 */ public String uploadFile(MultipartFile file) { String originalFilename = file.getOriginalFilename(); String fileSuffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1).toLowerCase(); // 只有當(dāng)滿足圖片格式時(shí)才進(jìn)來,重新賦圖片名,防止出現(xiàn)名稱重復(fù)的情況 String newFileName = UUID.randomUUID().toString().replaceAll("-", "") + "." + fileSuffix; // 該方法返回的為當(dāng)前項(xiàng)目的工作目錄,即在哪個(gè)地方啟動(dòng)的java線程 File fileTransfer = new File(fileUtils.getPath(), newFileName); try { file.transferTo(fileTransfer); log.info("頭像上傳: " + fileTransfer.getPath()); } catch (IOException e) { e.printStackTrace(); } // 將圖片相對(duì)路徑返回給前端 return "headimage/" + newFileName; } }
7. 測(cè)試
獲取默認(rèn)頭像的路徑url為
http://localhost:8080/{spring-application-name}/static/default.jpg
修改頭像
修改完成后, 返回相對(duì)路徑
訪問修改后的頭像
帶上相對(duì)路徑在url上直接可以訪問
到此這篇關(guān)于Springboot 上傳文件或頭像(MultipartFile、transferTo)的文章就介紹到這了,更多相關(guān)Springboot 上傳文件或頭像內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Springboot MultipartFile文件上傳與下載的實(shí)現(xiàn)示例
- SpringBoot 利用MultipartFile上傳本地圖片生成圖片鏈接的實(shí)現(xiàn)方法
- 關(guān)于springboot 中使用httpclient或RestTemplate做MultipartFile文件跨服務(wù)傳輸?shù)膯栴}
- 文件上傳SpringBoot后端MultipartFile參數(shù)報(bào)空問題的解決辦法
- 解決springboot 多線程使用MultipartFile讀取excel文件內(nèi)容報(bào)錯(cuò)問題
- 解決springboot MultipartFile文件上傳遇到的問題
- Springboot獲取文件內(nèi)容如何將MultipartFile轉(zhuǎn)File
相關(guān)文章
Mybatis-plus實(shí)現(xiàn)join連表查詢的示例代碼
mybatis-plus在連表查詢上是不行的,如果需要連表查詢,就得乖乖的去寫xml文件了,本文介紹了mybatis-plus-join框架,它支持連表查詢,感興趣的可以了解一下2023-08-08開放封閉原則_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理
這篇文章主要介紹了開放封閉原則,開放-封閉原則是面向?qū)ο笤O(shè)計(jì)的核心所在,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-08-08spring+springmvc整合mabytis時(shí)mapper注入失敗問題解決方法
這篇文章主要介紹了spring+springmvc整合mabytis時(shí)mapper注入失敗問題解決方法 ,需要的朋友可以參考下2017-08-08Java 字符串反轉(zhuǎn)實(shí)現(xiàn)代碼
這篇文章主要介紹了 Java 字符串反轉(zhuǎn)實(shí)現(xiàn)代碼的相關(guān)資料,需要的朋友可以參考下2017-03-03Java實(shí)現(xiàn)JDBC向數(shù)據(jù)庫(kù)批量插入
在Java項(xiàng)目中可能會(huì)出現(xiàn)大量向數(shù)據(jù)庫(kù)中插入的情況,本文主要介紹了Java實(shí)現(xiàn)JDBC向數(shù)據(jù)庫(kù)批量插入,具有一定的參考價(jià)值,感興趣的可以了解一下2023-09-09SpringMVC參數(shù)傳遞之基本數(shù)據(jù)類型和復(fù)雜對(duì)象說明
這篇文章主要介紹了SpringMVC參數(shù)傳遞之基本數(shù)據(jù)類型和復(fù)雜對(duì)象說明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-10-10Java多線程之ReentrantReadWriteLock源碼解析
這篇文章主要介紹了Java多線程之ReentrantReadWriteLock源碼解析,文中有非常詳細(xì)的代碼示例,對(duì)正在學(xué)習(xí)java基礎(chǔ)的小伙伴們有非常好的幫助,需要的朋友可以參考下2021-05-05