SpringBoot圖片上傳和訪問路徑映射
簡介
做移動端對接,框架用的SpringBoot,接口RESTful,實現一個圖片上傳功能,圖片上傳是個經典的應用場景了,完成后,做個筆記記錄一下,希望能幫到攻城獅們
開發(fā)步驟
1、先貼圖片上傳工具類
package com.prereadweb.utils;
import java.io.File;
import java.io.FileOutputStream;
import java.util.UUID;
/**
* @Description: 文件工具類
* @author: Yangxf
* @date: 2019/4/17 16:06
*/
public class FileTool {
/**
* @Function: 圖片上傳
* @author: YangXueFeng
* @Date: 2019/4/18 14:13
*/
public static void uploadFiles(byte[] file, String filePath, String fileName) throws Exception {
File targetFile = new File(filePath);
if (!targetFile.exists()) {
targetFile.mkdirs();
}
FileOutputStream out = new FileOutputStream(filePath + fileName);
out.write(file);
out.flush();
out.close();
}
/**
* @Function: 創(chuàng)建新的文件名
* @author: YangXueFeng
* @Date: 2019/4/17 17:57
*/
public static String renameToUUID(String fileName) {
return UUID.randomUUID() + "." + fileName.substring(fileName.lastIndexOf(".") + 1);
}
}
2、contoller層
/**
* @Function: 用戶圖片上傳
* @author: Yangxf
* @Date: 2019/4/17 15:42
*/
@PostMapping("/postfile")
public Object fileUpload(@RequestParam(value = "userImg", required = false) MultipartFile file, @RequestParam(value = "userId", required = false) Long userId) {
return personalService.fileUpload(file, userId);
}
此處提一下@RequestParam注解
value:前臺所傳參數的名稱
required:它有兩個參數,true/false,默認是true,如果設置的是true的,客戶端如果傳值為空的話,訪問此接口會報500異常,如果是false的話,客戶端傳值為空,會默認給參數賦值null
3、service層
/**
* @Function: 用戶頭像上傳
* @author: YangXf
* @Date: 2019/4/17 15:41
* @param: file 圖片
* @param: userId 用戶ID
* @return: map
*/
@Override
public Map<String, Object> fileUpload(MultipartFile file, Long userId) {
Map<String, Object> map = new HashMap<>();
if (Util.isEmpty(file)) {
System.out.println("文件為空空");
map.put("code", UserStatusEnum.EMPTY.intKey());
map.put("msg", UserStatusEnum.EMPTY.value());
return map;
}
UserEntity user = userMapper.fetchUser(userId);
if(Util.isEmpty(user)){
map.put("code", UserStatusEnum.USER_NOT_EXISTENCE.intKey());
map.put("msg", UserStatusEnum.USER_NOT_EXISTENCE.value());
return map;
}
String fileName = file.getOriginalFilename();
fileName = FileTool.renameToUUID(fileName);
try {
FileTool.uploadFiles(file.getBytes(), uploadConfig.getUploadPath(), fileName);
} catch (Exception e) {
}
if (Util.isEmpty(fileName)) {
map.put("code", UserStatusEnum.USER_NOT_EXISTENCE.intKey());
map.put("msg", UserStatusEnum.USER_NOT_EXISTENCE.value());
return map;
}
Map<String, Object> returnMap = new HashMap<>();
String url = "/static/" + fileName;
updateUrl(userId, url);
returnMap.put("imageUrl", url);
map.put("code", UserStatusEnum.SUCCESS.intKey());
map.put("msg", UserStatusEnum.SUCCESS.value());
map.put("data", returnMap);
return map;
}
4、設置圖片訪問路徑映射
preread: #文件上傳目錄(注意Linux和Windows上的目錄結構不同) uploadPath: E:/image/
5、配置文件上傳路徑
package com.prereadweb.config.upload;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* @Description: 文件上傳路徑配置
* @author: Yangxf
* @date: 2019/4/17 17:50
*/
@Component
@ConfigurationProperties(prefix="preread")
public class PreReadUploadConfig {
//上傳路徑
private String uploadPath;
public String getUploadPath() {
return uploadPath;
}
public void setUploadPath(String uploadPath) {
this.uploadPath = uploadPath;
}
}
6、配置映射路徑
package com.prereadweb.config.upload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
* @Description: 自定義資源映射
* <p>
* 設置虛擬路徑,訪問絕對路徑下資源
* </p>
* @author: Yangxf
* @date: 2019/4/17 18:17
*/
@ComponentScan
@Configuration
public class WebConfigurer extends WebMvcConfigurerAdapter {
@Autowired
PreReadUploadConfig uploadConfig;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("file:///"+uploadConfig.getUploadPath());
}
}
7、此處需要導入一個jar報
<!-- 配置 --> <dependency> <groupId> org.springframework.boot </groupId> <artifactId> spring-boot-configuration-processor </artifactId> <optional> true </optional> </dependency>
8、postman測試接口

9、此時配置完成
圖片的存儲路徑在:E:/image/
訪問路徑:http://127.0.0.1:8080/static/0fa7481d-4fec-42c3-a716-514feff73707.jpg
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
解決spring 處理request.getInputStream()輸入流只能讀取一次問題
這篇文章主要介紹了解決spring 處理request.getInputStream()輸入流只能讀取一次問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-09-09
SpringBoot如何通過Feign調用傳遞Header中參數
這篇文章主要介紹了SpringBoot通過Feign調用傳遞Header中參數,本文給大家分享兩種解決方案給大家詳細講解,需要的朋友可以參考下2023-04-04
JDK1.8源碼下載及idea2021導入jdk1.8源碼的詳細步驟
這篇文章主要介紹了JDK1.8源碼下載及idea2021導入jdk1.8源碼的詳細步驟,在文章開頭就給大家分享了JDK1.8源碼下載地址和下載步驟,告訴大家idea2021.1.3導入JDK1.8源碼步驟,需要的朋友可以參考下2022-11-11
Java基于ServletContextListener實現UDP監(jiān)聽
這篇文章主要介紹了Java基于ServletContextListener實現UDP監(jiān)聽,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2019-12-12

