版本聲明:
springBoot: 1.5.9
jdk: 1.8
IDE: IDEA
注:此項目先後端分離java
使用的方法是配置靜態目錄(相似tomcat的虛擬目錄映射)web
一、配置靜態目錄spring
upload: image: path: G:/image/ spring: resources: #配置靜態路徑,多個可用逗號隔開 static-locations: classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,file:${upload.image.path}
二、編寫圖片上傳工具類json
問題: 工具類有個字段是靜態的,沒法使用spring注入。 採用間接注入的方式注入後端
@Resource(name = "uploadProperty") private UploadProperty tempUploadProperty; private static UploadProperty uploadProperty; // 在servlet中 會在構造函數以後執行, 一樣能夠實現 InitializingBean 接口 @PostConstruct private void init(){ uploadProperty = tempUploadProperty; }
以上代碼注意2處。
一、需使用@Resource註解,注入Bean。使用@Autowired 註解報錯。 使用@Resource 註解 報 有2個相同的bean。可是個人工程中,卻只有1個UploadProperty。因此帶上Bean的名字tomcat
二、@PostConstruct:該註解會在構造函數以後執行,或者,你也能夠實現InitializingBean接口。 須要說明的是,工具類,須要使用@Component 來讓其被spring管理。 由於。 @PostConstruct 影響的是受spring管理bean的生命週期。服務器
三、圖片的回顯
圖片的回顯,你只需將圖片的地址返給客戶端便可。
例如: 你配置的靜態目錄是 D:/images/ 。 若是你圖片的完整路徑是D:/images/test/12.png。
那麼,你回顯成 http://ip/test/12.png。 便可app
四、完整代碼前後端分離
application.ymldom
server: port: 9999 context-path: / upload: #圖片上傳 image: path: G:/image/ max-size: 2 #單位MB accept-type: - image/png - image/jpeg - image/jpg spring: resources: #配置靜態路徑,多個可用逗號隔開 static-locations: classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,file:${upload.image.path}
IOUtils
package com.hycx.common.util; import org.springframework.util.StringUtils; import javax.servlet.http.HttpServletRequest; /** * @author 陳少平 * @description * @create in 2018/2/11 23:13 */ public class HttpUtil { /** * 獲取客戶端真實IP地址。需考慮客戶端是代理上網 * @param request * @return 客戶端真實IP地址 */ public static String getClientIp(HttpServletRequest request){ if(StringUtils.isEmpty(request.getHeader("x-forwarded-for"))) { return request.getRemoteAddr(); } return request.getHeader("x-forwarded-for"); } /** * 獲取服務器地址 Http://localhost:8080/ 相似 * @param request * @return */ public static String serverBasePath(HttpServletRequest request) { return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath(); } }
UploadProperty
package com.hycx.common.property; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; import java.util.ArrayList; import java.util.List; /** * @author 陳少平 * @description * @create in 2018/2/14 23:22 */ @Component @ConfigurationProperties(prefix = "upload.image") public class UploadProperty { private String path; private int maxSize; private List<String> acceptType = new ArrayList<>(); public UploadProperty() { } @Override public String toString() { return "UploadProperty{" + "path='" + path + '\'' + ", maxSize=" + maxSize + ", acceptType=" + acceptType + '}'; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public int getMaxSize() { return maxSize; } public void setMaxSize(int maxSize) { this.maxSize = maxSize; } public List<String> getAcceptType() { return acceptType; } public void setAcceptType(List<String> acceptType) { this.acceptType = acceptType; } }
UploadUtils
package com.hycx.common.util; import com.hycx.common.exception.ImageAcceptNotSupportException; import com.hycx.common.exception.ImageMaxSizeOverFlow; import com.hycx.common.property.UploadProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.stereotype.Component; import org.springframework.web.multipart.MultipartFile; import javax.annotation.PostConstruct; import javax.annotation.Resource; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.time.LocalDate; import java.util.List; import java.util.UUID; /** * @author 陳少平 * @description * @create in 2018/2/14 20:42 */ @Component @EnableConfigurationProperties(UploadProperty.class) public class UploadUtil { //spring 中沒法注入靜態變量,只能經過間接注入的方式,使用 @AutoWired直接報錯,使用Resource時 // 直接報找到了2個一樣的bean,可是我其實只有1個這樣的Bean。 @Resource(name = "uploadProperty") private UploadProperty tempUploadProperty; private static UploadProperty uploadProperty; // 在servlet中 會在構造函數以後執行, 一樣能夠實現 InitializingBean 接口 @PostConstruct private void init(){ uploadProperty = tempUploadProperty; } /** * 圖片上傳,默認支持全部格式的圖片, 文件默認最大爲 2MB * @param file * @return 圖片存儲路徑 */ public static String uploadImage(MultipartFile file){ return uploadImageByAcceptType(file,uploadProperty.getAcceptType(),uploadProperty.getMaxSize()); } /** * 圖片上傳,默認支持全部格式的圖片 * @param file * @param maxSize 文件最大多少,單位 mb * @return 圖片存儲路徑 */ public static String uploadImage(MultipartFile file,int maxSize){ return uploadImageByAcceptType(file,uploadProperty.getAcceptType(),uploadProperty.getMaxSize()); } /** * 上傳圖片(可限定文件類型) * @param file * @param acceptTypes "image/png image/jpeg image/jpg" * @param maxSize 文件最大爲2MB * @return 圖片存儲路徑。 */ public static String uploadImageByAcceptType(MultipartFile file, List<String> acceptTypes,int maxSize){ String type = file.getContentType(); if(!acceptTypes.contains(type)){ throw new ImageAcceptNotSupportException(); } int size = (int) Math.ceil(file.getSize() / 1024 /1024); if(size > maxSize) { throw new ImageMaxSizeOverFlow(); } String originalFilename = file.getOriginalFilename(); String suffix = originalFilename.substring(originalFilename.lastIndexOf(".")); LocalDate now = LocalDate.now(); String year = now.getYear()+""; String month = now.getMonth().getValue()+""; String day = now.getDayOfMonth()+""; Path path = Paths.get(uploadProperty.getPath(), year, month, day); String filePath = path.toAbsolutePath().toString(); File fileDir = new File(filePath); fileDir.mkdirs(); String uuid = UUID.randomUUID().toString() + suffix; File realFile = new File(fileDir, uuid); try { IOUtils.copy(file.getInputStream(),new FileOutputStream(realFile)); } catch (IOException e) { e.printStackTrace(); } String tempPath = "/"+year+"/"+month+"/"+day+"/"+uuid; return tempPath; }
HttpUtils
package com.hycx.common.util; import org.springframework.util.StringUtils; import javax.servlet.http.HttpServletRequest; /** * @author 陳少平 * @description * @create in 2018/2/11 23:13 */ public class HttpUtil { /** * 獲取客戶端真實IP地址。需考慮客戶端是代理上網 * @param request * @return 客戶端真實IP地址 */ public static String getClientIp(HttpServletRequest request){ if(StringUtils.isEmpty(request.getHeader("x-forwarded-for"))) { return request.getRemoteAddr(); } return request.getHeader("x-forwarded-for"); } /** * 獲取服務器地址 Http://localhost:8080/ 相似 * @param request * @return */ public static String serverBasePath(HttpServletRequest request) { return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath(); } }
controller
@PostMapping("/avatar") public Object updateAvatar(String userName, @RequestParam("file") MultipartFile file, HttpServletRequest request) { JSONObject jsonObject = new JSONObject(); User user = userService.getUserByUserName(userName); if(Objects.isNull(user)) { jsonObject.put("code",HttpEnum.E_90003.getCode()); jsonObject.put("msg",HttpEnum.E_90003.getMsg()); return jsonObject; } String imagePath; try{ imagePath = UploadUtil.uploadImage(file); System.out.println("imagePath"+ imagePath); }catch (ImageAcceptNotSupportException ex) { jsonObject.put("code", HttpEnum.E_40002.getCode()); jsonObject.put("msg", HttpEnum.E_40002.getMsg()); return jsonObject; }catch (ImageMaxSizeOverFlow ex) { jsonObject.put("code", HttpEnum.E_40003.getCode()); jsonObject.put("msg", HttpEnum.E_40003.getMsg()); return jsonObject; } System.out.println(" basePath === "+HttpUtil.serverBasePath(request)); String msg = HttpUtil.serverBasePath(request) + imagePath; jsonObject.put("code", HttpEnum.OK.getCode()); jsonObject.put("msg", msg); return jsonObject; }