UploadController.java:
package com.example.demo.controller; import com.alibaba.fastjson.JSONObject; import com.example.demo.common.*; import org.apache.commons.io.FileUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.util.CollectionUtils; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import java.io.File; import java.net.URL; import java.util.Map; @RestController public class UploadController { @Autowired private SysConfigs sysConfigs; /** * 文件上傳 * * @param file * @return */ @PostMapping("/upload-file") public ResponseEntity<String> imgSearchUpload( @RequestParam(value = "fileName") MultipartFile file) throws Exception { if (null != file) { String fileName = file.getOriginalFilename(); String suffix = fileName.substring(fileName.lastIndexOf(".")); String newFileName = DateUtil.getTimeMillis() + suffix; String realPath = this.getUploadFilePath(newFileName); try { File tempFile = new File(realPath); if (!tempFile.exists()) { if (!tempFile.getParentFile().exists()) { tempFile.getParentFile().mkdirs(); } tempFile.createNewFile(); } file.transferTo(tempFile); JSONObject json = new JSONObject(); json.put("realPath", realPath); json.put("filename", newFileName); return ResponseEntity.ok().body(json.toJSONString()); } catch (Exception e) { throw new Exception(e.getMessage()); } } else { throw new Exception("上傳的圖片文件為null"); } } /** * 圖片上傳base64 * * @param request * @return */ @PostMapping("/upload-base64") public ResponseEntity<String> imgSearchUploadBASE64(HttpServletRequest request) throws Exception { String codeBase64 = request.getParameter("codeBase64"); if (null != codeBase64 && !"".equals(codeBase64)) { String newFileName = DateUtil.getTimeMillis() + ".jpg"; String realPath = this.getUploadFilePath(newFileName); try { ImageUtil.base64ToImage(codeBase64, realPath); JSONObject json = new JSONObject(); json.put("realPath", realPath); json.put("filename", newFileName); return ResponseEntity.ok().body(json.toJSONString()); } catch (Exception e) { throw new Exception(e.getMessage()); } } else { throw new Exception("上傳的圖片文件為null"); } } /** * 文件網絡連接方式上傳 * * @param fileUrl * @return * @throws Exception */ @PostMapping("/upload-url-file") public ResponseEntity<String> searchImageByUrl(@RequestParam("fileUrl") String fileUrl) throws Exception { if (null != fileUrl) { try { URL url = WebUtil.normalizedURL(fileUrl); if (url.getProtocol().toLowerCase().startsWith("http")) { String suffix = FileUtil.suffixFromUrl(url.toString()); String[] suffixs = sysConfigs.getUpload().get("imgSuffix").toLowerCase().split(","); if (CollectionUtils.arrayToList(suffixs).contains(suffix.toLowerCase())) { String newFileName = DateUtil.getTimeMillis() + "." + suffix; String realPath = this.getUploadFilePath(newFileName); File realFile = new File(realPath); FileUtils.copyURLToFile(url, realFile); JSONObject json = new JSONObject(); json.put("realPath", realPath); json.put("filename", newFileName); return ResponseEntity.ok().body(json.toJSONString()); } else { throw new Exception("圖片上傳失敗,請重新上傳!"); } } else { throw new Exception("請輸入正確的網址格式"); } } catch (Exception e) { throw new Exception(e.getMessage()); } } else { throw new Exception("請輸入網址"); } } /** * 獲取圖片上傳路徑 * * @param filename * @return */ private String getUploadFilePath(String filename) { Map<String, String> upConfig = sysConfigs.getUpload(); return upConfig.get("base") + upConfig.get("imgDir") + filename; } }
圖片與base64相互轉換類 ImageUtil.java:
package com.example.demo.common; import lombok.extern.slf4j.Slf4j; import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.util.Objects; @Slf4j public class ImageUtil { /** * base64轉圖片 * @param base64Code 圖片的base64碼 * @param imgPath 最終圖片存放的路徑 * @throws IOException 異常 */ public static void base64ToImage(String base64Code, String imgPath) throws IOException { FileOutputStream fos = null; try{ if (base64Code.split(",").length > 1) { base64Code = base64Code.split(",")[1]; } BASE64Decoder decoder = new BASE64Decoder(); // Base64解碼 byte[] bytes = decoder.decodeBuffer(base64Code); for (int i = 0; i < bytes.length; ++i) { if (bytes[i] < 0) {// 調整異常數據 bytes[i] += 256; } } fos = new FileOutputStream(imgPath); fos.write(bytes); fos.flush(); } finally{ try { if (null != fos) fos.close(); } catch (IOException e) { log.error("流關閉異常!" + e); } } } /** * 網絡圖片轉換Base64的方法 * * @param netImagePath */ private static void netImage2Base64(String netImagePath) { final ByteArrayOutputStream data = new ByteArrayOutputStream(); try { // 創建URL URL url = new URL(netImagePath); final byte[] by = new byte[1024]; // 創建鏈接 final HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(5000); new Thread(new Runnable() { @Override public void run() { try { InputStream is = conn.getInputStream(); // 將內容讀取內存中 int len = -1; while ((len = is.read(by)) != -1) { data.write(by, 0, len); } // 對字節數組Base64編碼 BASE64Encoder encoder = new BASE64Encoder(); String strNetImageToBase64 = encoder.encode(data.toByteArray()); // System.out.println("網絡圖片轉換Base64:" + strNetImageToBase64); // 關閉流 is.close(); } catch (IOException e) { e.printStackTrace(); } } }).start(); } catch (IOException e) { e.printStackTrace(); } } /** * 本地圖片轉換Base64的方法 * * @param imgPath */ public static String image2Base64(String imgPath) throws IOException { InputStream is = null; byte[] data; // 讀取圖片字節數組 try { is = new FileInputStream(imgPath); data = new byte[is.available()]; is.read(data); } finally{ try { if (null != is) is.close(); } catch (IOException e) { log.error("流關閉異常!" + e); } } // 對字節數組Base64編碼 BASE64Encoder encoder = new BASE64Encoder(); // 返回Base64編碼過的字節數組字符串 // System.out.println("本地圖片轉換Base64:" + encoder.encode(Objects.requireNonNull(data))); return encoder.encode(Objects.requireNonNull(data)); } public static void main(String[] args) { try { ImageUtil.image2Base64("E:\\home\\hgk\\img\\20210610152446262.jpg"); } catch (IOException e) { e.printStackTrace(); } } }
WebUtil.java:
package com.example.demo.common; import io.mola.galimatias.GalimatiasParseException; import javax.servlet.http.HttpServletRequest; import java.net.MalformedURLException; import java.net.URL; import java.util.HashMap; import java.util.Iterator; import java.util.Map; /** * @author : kl * create : 2020-12-27 1:30 上午 **/ public class WebUtil { /** * 獲取標准的URL * @param urlStr url * @return 標准的URL */ public static URL normalizedURL(String urlStr) throws GalimatiasParseException, MalformedURLException { return io.mola.galimatias.URL.parse(urlStr).toJavaURL(); } /** * 獲取url中的參數 * * @param url url * @param name 參數名 * @return 參數值 */ public static String getUrlParameterReg(String url, String name) { Map<String, String> mapRequest = new HashMap<>(); String strUrlParam = truncateUrlPage(url); if (strUrlParam == null) { return ""; } //每個鍵值為一組 String[] arrSplit = strUrlParam.split("[&]"); for (String strSplit : arrSplit) { String[] arrSplitEqual = strSplit.split("[=]"); //解析出鍵值 if (arrSplitEqual.length > 1) { //正確解析 mapRequest.put(arrSplitEqual[0], arrSplitEqual[1]); } else if (!arrSplitEqual[0].equals("")) { //只有參數沒有值,不加入 mapRequest.put(arrSplitEqual[0], ""); } } return mapRequest.get(name); } /** * 去掉url中的路徑,留下請求參數部分 * * @param strURL url地址 * @return url請求參數部分 */ private static String truncateUrlPage(String strURL) { String strAllParam = null; strURL = strURL.trim(); String[] arrSplit = strURL.split("[?]"); if (strURL.length() > 1) { if (arrSplit.length > 1) { if (arrSplit[1] != null) { strAllParam = arrSplit[1]; } } } return strAllParam; } /** * 從url中剝離出文件名 * * @param url * @return 文件名 */ public static String getFileNameFromURL(String url) { // 因為url的參數中可能會存在/的情況,所以直接url.lastIndexOf("/")會有問題 // 所以先從?處將url截斷,然后運用url.lastIndexOf("/")獲取文件名 String noQueryUrl = url.substring(0, url.contains("?") ? url.indexOf("?") : url.length()); return noQueryUrl.substring(noQueryUrl.lastIndexOf("/") + 1); } /** * 把request轉為map * * @param request * @return */ public static Map<String, Object> getParameterMap(HttpServletRequest request) { // 參數Map Map<?, ?> properties = request.getParameterMap(); // 返回值Map Map<String, Object> returnMap = new HashMap<String, Object>(); Iterator<?> entries = properties.entrySet().iterator(); Map.Entry<String, Object> entry; String name = ""; String value = ""; Object valueObj =null; while (entries.hasNext()) { entry = (Map.Entry<String, Object>) entries.next(); name = (String) entry.getKey(); valueObj = entry.getValue(); if (null == valueObj) { value = ""; } else if (valueObj instanceof String[]) { String[] values = (String[]) valueObj; for (int i = 0; i < values.length; i++) { value = values[i] + ","; } value = value.substring(0, value.length() - 1); } else { value = valueObj.toString(); } returnMap.put(name, value); } return returnMap; } }
這其中會引入一些外部依賴,其中WebUtil里的一個url驗證的url規范化依賴:
<!-- url 規范化 --> <dependency> <groupId>io.mola.galimatias</groupId> <artifactId>galimatias</artifactId> <version>0.2.1</version> </dependency>
網絡文件拷貝方法FileUtils.copyURLToFile依賴:
<dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.6</version> </dependency>
每天進步一點點,點滴記錄,積少成多。
以此做個記錄,
如有不足之處還望多多留言指教!
