fhx
2024-03-25 0b6e556313e5626f335a5b4b590a1c495238170b
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;
@@ -42,8 +44,7 @@
    /**
     * 获取文件base64字符串
     * @param urlPath  文件路径
     * @return
     * @throws IOException
     * @return 返回base64编码
     */
    public static String getFileBaseStrByUrl(String urlPath) throws IOException {
        InputStream is = getUrlFile(urlPath);
@@ -108,7 +109,7 @@
        File file = null;
        try {
            File dir = new File(filePath);
            if(!dir.exists()&&dir.isDirectory()){//判断文件目录是否存在
            if(!dir.exists()){//判断文件目录是否存在
                dir.mkdirs();
            }
            file = new File(filePath+"\\"+fileName);
@@ -299,5 +300,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;
    }
}