一、1.1(關鍵)映射配置(親測可用)
import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; /** * @author zhangjiahao */ @Configuration public class WebMvcConfig implements WebMvcConfigurer { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { /** * 資源映射路徑 * addResourceHandler:訪問映射路徑 * addResourceLocations:資源絕對路徑 */ registry.addResourceHandler("/upload/**").addResourceLocations("file:D:/upload/"); } }
1.2 有攔截器的話需要放行upload目錄(InterceptorConfig是攔截器的類名,根據自己項目類自行修改)
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; /** * @author zhangjiahao * @date 2020/1/10 16:04 */ @Configuration public class LoginConfig implements WebMvcConfigurer { @Bean public InterceptorConfig interceptorConfig(){ return new InterceptorConfig(); } @Override public void addInterceptors(InterceptorRegistry registry) { //注冊TestInterceptor攔截器 InterceptorRegistration registration= registry.addInterceptor(new InterceptorConfig()); registration.addPathPatterns("/**"); //所有路徑都被攔截 registration.excludePathPatterns( //添加不攔截路徑 "/***", //登錄 "/upload/**" //圖片 ); } }
二、MultipartFile上傳圖片代碼
文中的uploadDir上傳文件的路徑,我是springboot項目,在配置文件中配置的


@RequestMapping(value = "/upload") public String upload(@RequestParam(value = "file") MultipartFile file) throws IOException { // 獲取文件名 String fileName = file.getOriginalFilename(); // 獲取文件的后綴名 String suffixName = fileName.substring(fileName.lastIndexOf(".")); List<String> extList = Arrays.asList(".jpg", ".png", ".jpeg", ".gif"); if (!extList.contains(suffixName)) { return "圖片格式非法"; } // 解決中文問題,liunx下中文路徑,圖片顯示問題 fileName = UUID.randomUUID().toString().replace("-", "") + suffixName; // 返回客戶端 文件地址 URL String url = "localhost:8080"+"/upload/" + fileName; File dest = new File( uploadDir + fileName); // 檢測是否存在目錄 if (!dest.getParentFile().exists()) { dest.getParentFile().mkdirs(); } file.transferTo(dest); return url; }
三、MultipartFile轉為base64類型上傳圖片代碼(根據自己的實際代碼改動即可)
@RequestMapping(value = "/uploadBase64") public Object upload(@RequestParam String image) throws IOException { try { // image格式: "data:image/png;base64," + "圖片的base64字符串" MultipartFile multipartFile = Base64Util.base64ToMultipart(image); String originalFilename = multipartFile.getOriginalFilename(); // 文件擴展名 String ext = originalFilename.substring(originalFilename.lastIndexOf(".")).trim(); List<String> extList = Arrays.asList(".jpg", ".png", ".jpeg", ".gif"); if (!extList.contains(ext)) { return new BaseResult(HttpStatus.INTERNAL_SERVER_ERROR,"圖片格式非法"); } String randomFilename = UUID.randomUUID().toString().replace("-", "") + ext; //將文件寫入服務器 String fileLocalPath = uploadDir + randomFilename; File localFile = new File(fileLocalPath); multipartFile.transferTo(localFile); InetAddress address = InetAddress.getLocalHost(); //寫入服務器成功后組裝返回的數據格式 return new BaseResult(HttpStatus.OK,address.getHostAddress()+":8080/upload/" + randomFilename); } catch (Exception e) { logger.error("上傳圖片失敗:", e); } return new BaseResult(HttpStatus.INTERNAL_SERVER_ERROR); }
import lombok.extern.slf4j.Slf4j; import org.springframework.web.multipart.MultipartFile; import sun.misc.BASE64Decoder; import java.io.IOException; /** * @author zhangjiahao */ @Slf4j public class Base64Util { public static MultipartFile base64ToMultipart(String base64) { try { String[] baseStr = base64.split(","); BASE64Decoder decoder = new BASE64Decoder(); byte[] b = new byte[0]; b = decoder.decodeBuffer(baseStr[1]); for(int i = 0; i < b.length; ++i) { if (b[i] < 0) { b[i] += 256; } } return new BASE64DecodedMultipartFile(b, baseStr[0]); } catch (IOException e) { log.error(e.getMessage()); return null; } } }
import org.springframework.web.multipart.MultipartFile; import java.io.*; /** * 自定義的MultipartFile的實現類,主要用於base64上傳,以下方法都可以根據實際項目自行實現 * * @author zhangjiahao */ public class BASE64DecodedMultipartFile implements MultipartFile { private final byte[] imgContent; private final String header; public BASE64DecodedMultipartFile(byte[] imgContent, String header) { this.imgContent = imgContent; this.header = header.split(";")[0]; } @Override public String getName() { return System.currentTimeMillis() + Math.random() + "." + header.split("/")[1]; } @Override public String getOriginalFilename() { return System.currentTimeMillis() + (int) Math.random() * 10000 + "." + header.split("/")[1]; } @Override public String getContentType() { return header.split(":")[1]; } @Override public boolean isEmpty() { return imgContent == null || imgContent.length == 0; } @Override public long getSize() { return imgContent.length; } @Override public byte[] getBytes() throws IOException { return imgContent; } @Override public InputStream getInputStream() throws IOException { return new ByteArrayInputStream(imgContent); } @Override public void transferTo(File dest) throws IOException, IllegalStateException { new FileOutputStream(dest).write(imgContent); } }
四、解析base64為圖片並上傳
public String Base64GenerateImage(@RequestParam String imgStr) throws Exception { if (imgStr == null){ // 圖像數據為空 return "圖片不能為空"; } BASE64Decoder decoder = new BASE64Decoder(); // Base64解碼,對字節數組字符串進行Base64解碼並生成圖片 imgStr = imgStr.replaceAll(" ", "+"); byte[] b = decoder.decodeBuffer(imgStr.replace("data:image/png;base64,", "")); for (int i = 0; i < b.length; ++i) { if (b[i] < 0) {// 調整異常數據 b[i] += 256; } } String imgName = System.currentTimeMillis() + ".png"; String dbUrl = ""; // 生成圖片 String imgFilePath = uploadDir + imgName;//新生成的圖片 OutputStream out = new FileOutputStream(imgFilePath); out.write(b); out.flush(); out.close(); dbUrl = uploadDir + imgName; return dbUrl; }
