Base64 转MultipartFile 或者保存到本地

`

这里是为了Feign调用上传使用, 因为MockMultipartFile feign调用会失败

import org.apache.commons.fileupload.disk.DiskFileItem;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;

public class Base64ToFile {
public static MultipartFile saveBase64ToMultipartFile(String base64, String fileName) {
MultipartFile multipartFile = null;
File file = null;

    try {
        // 去掉Base64字符串中的前缀 "data:image/png;base64,"
        if (base64.contains(",")) {
            base64 = base64.split(",")[1];
        }

        // 修复Base64字符串中的空格替换为加号
        base64 = base64.replace(" ", "+");

        // 解码Base64字符串
        byte[] decodedBytes = Base64.getDecoder().decode(base64);

        // 获取Windows桌面路径
        String desktopPath = System.getProperty("user.home") + "\\Desktop";
        String filePath = Paths.get(desktopPath, fileName).toString();
        file = new File(filePath);

        // 写入文件
        try (OutputStream os = Files.newOutputStream(file.toPath())) {
            os.write(decodedBytes);
        }

        // 确保文件存在
        if (!file.exists()) {
            throw new IllegalArgumentException("文件不存在: " + filePath);
        }

        // 创建 DiskFileItem
        DiskFileItem fileItem = new DiskFileItem(
                "file", // fieldName
                Files.probeContentType(file.toPath()), // contentType
                true, // isFormField
                fileName, // fileName
                (int) file.length(), // size
                file.getParentFile() // repository
        );

        // 写入 DiskFileItem
        try (InputStream input = Files.newInputStream(file.toPath());
             OutputStream output = fileItem.getOutputStream()) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = input.read(buffer)) != -1) {
                output.write(buffer, 0, bytesRead);
            }
            output.flush();
        }

        // 创建 MultipartFile
        multipartFile = new CommonsMultipartFile(fileItem);

        // 删除保存的文件
        if (file.delete()) {
            System.out.println("文件已删除: " + filePath);
        } else {
            System.out.println("文件删除失败: " + filePath);
        }

    } catch (IOException e) {
        e.printStackTrace();
    }

    return multipartFile;
}

}

`

posted @ 2024-08-26 14:24  Rick_Leee  阅读(379)  评论(0)    收藏  举报