关于springboot文件上传,图片base64上传,网络文件上传
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>
每天进步一点点,点滴记录,积少成多。
以此做个记录,
如有不足之处还望多多留言指教!