From 0a4d0a2f2c0b36210c62d5e2b215a0e1eac36e02 Mon Sep 17 00:00:00 2001 From: fhx <308050795@qq.com> Date: 星期五, 21 七月 2023 16:23:19 +0800 Subject: [PATCH] 1.新增文件处理方法 --- src/main/java/com/hx/util/FileConvertTool.java | 32 ++++++++++++++++++++++++++++++++ 1 files changed, 32 insertions(+), 0 deletions(-) diff --git a/src/main/java/com/hx/util/FileConvertTool.java b/src/main/java/com/hx/util/FileConvertTool.java index a57a0fd..1598f98 100644 --- a/src/main/java/com/hx/util/FileConvertTool.java +++ b/src/main/java/com/hx/util/FileConvertTool.java @@ -1,5 +1,6 @@ package com.hx.util; +import com.hx.exception.TipsException; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.io.IOUtils; @@ -7,6 +8,7 @@ import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.commons.CommonsMultipartFile; import sun.misc.BASE64Decoder; +import sun.misc.BASE64Encoder; import java.io.*; import java.net.URL; @@ -299,5 +301,35 @@ } } + public static String encodeBase64File(File file) throws Exception { + FileInputStream fileInputStream = new FileInputStream(file); + byte[] bytes = new byte[fileInputStream.available()]; + // 璇诲彇鍒� byte 閲岄潰 + fileInputStream.read(bytes); + fileInputStream.close(); + BASE64Encoder base64Encoder = new BASE64Encoder(); + // 寰楀埌鏂囦欢 涔嬪悗杞垚beye 鐒跺悗浣跨敤base64杞爜 + // 杞爜 + String encode = base64Encoder.encode(bytes); + return encode; + } + public static String encodeBase64File(MultipartFile multipartFile) throws Exception { + if (multipartFile == null) { + throw new TipsException("鏈鏌ュ埌涓婁紶鐨勬枃浠讹紒"); + } + String imageBaseStr = null; + try { + String contentType = multipartFile.getContentType(); + byte[] imageBytes = multipartFile.getBytes(); + BASE64Encoder base64Encoder = new BASE64Encoder(); +// imageBaseStr = "data:" + contentType + ";base64," + base64Encoder.encode(imageBytes); + imageBaseStr = base64Encoder.encode(imageBytes); + imageBaseStr = imageBaseStr.replaceAll("[\\s*\t\n\r]", ""); + } catch (IOException e) { + throw new TipsException("鏂囦欢杞崲base64寮傚父"); + } + //杩斿洖鐢熸垚鐨勭紪鐮� + return imageBaseStr; + } } -- Gitblit v1.8.0