springboot中Base64\MultipartFile\File对象互转

首先新建FileUtil.java

package com.demo.util;

import org.springframework.lang.Nullable;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/** file工具
 * author xiaochi
 * date 2024/9/23
 */
public class FileUtil {

    /**
     * MultipartFile对象转File
     * @param file
     * @return
     * @throws Exception
     */
    public static File multipartFileToFile(MultipartFile file) throws Exception {
        File convFile = new File(file.getOriginalFilename());
        if (convFile.createNewFile()){
            try (InputStream in = file.getInputStream(); OutputStream out = new FileOutputStream(convFile)) {
                int byteRead = 0;
                byte[] buffer = new byte[4096];
                while ((byteRead = in.read(buffer)) != -1) {
                    out.write(buffer, 0, byteRead);
                }
            }
        }
        return convFile;
    }

    /**
     * Base64格式图片转input输入流
     * @throws Exception
     */
    public static InputStream base64ToInputStream(String base64Str) throws Exception {
        byte[] bytes = base64ToByteArray(base64Str);
        return new ByteArrayInputStream(bytes);
    }

    /**
     * InputStream转Base64格式
     * @throws Exception
     */
    public static String toBase64(InputStream in) throws Exception {
        return toBase64(in,"jpg");
    }

    /**
     * Base64格式图片转byte[]数组
     * @throws Exception
     */
    public static byte[] base64ToByteArray(String base64Str) throws Exception {
        base64Str = base64Str.replaceAll("data:image/(jpg|png|jpeg);base64,","");
        return Base64.getDecoder().decode(base64Str);
    }

    /**
     * InputStream转Base64格式
     * @throws Exception
     */
    public static String toBase64(InputStream in,String imageType) throws Exception {
        byte[] bytes = new byte[4096];
        int len;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        while ((len = in.read(bytes)) != -1){
            out.write(bytes,0,len);
        }
        out.flush();
        return "data:image/"+imageType+";base64,"+ new String(Base64.getEncoder().encode(out.toByteArray()), StandardCharsets.UTF_8);
    }

    /**
     * Base64格式图片转MultipartFile对象
     * 调用:FileUtil.base64ToMultipartFile("123.jpg", "123.jpg", "jpg", Base64格式图片字符串);
     * @throws Exception
     */
    public static MultipartFile base64ToMultipartFile(String fileName,String originalFilename,String contentType,String base64Str) throws Exception {
        byte[] bytes = base64ToByteArray(base64Str);
        return new DefaultMultiPartFile(fileName,originalFilename,contentType, bytes);
    }

    /**
     * File转MultipartFile对象
     * 调用:FileUtil.base64ToMultipartFile("123.jpg", "123.jpg", "jpg", 文件字节数组);
     * @throws Exception
     */
    public static MultipartFile fileToMultipartFile(String fileName,String originalFilename,String contentType,byte[] content) throws Exception {
        return new DefaultMultiPartFile(fileName,originalFilename,contentType, content);
    }

    public static class DefaultMultiPartFile implements MultipartFile {
        private final String name;
        private String originalFilename;
        @Nullable
        private String contentType;
        private final byte[] content;

        public DefaultMultiPartFile(String name, @Nullable byte[] content) {
            this(name, name, (String)null, content);
        }

        public DefaultMultiPartFile(String name, String originalFilename, @Nullable String contentType, byte[] content) {
            this.name = name;
            this.originalFilename = originalFilename;
            this.contentType = contentType;
            this.content = content;
        }

        @Override
        public String getName() {
            return this.name;
        }

        @Override
        public String getOriginalFilename() {
            return this.originalFilename;
        }

        @Override
        public String getContentType() {
            return this.contentType;
        }

        @Override
        public boolean isEmpty() {
            return content.length==0;
        }

        @Override
        public long getSize() {
            return content.length;
        }

        @Override
        public byte[] getBytes() throws IOException {
            return content;
        }

        @Override
        public InputStream getInputStream() throws IOException {
            return new ByteArrayInputStream(content);
        }

        @Override
        public void transferTo(File file) throws IOException, IllegalStateException {
            FileCopyUtils.copy(this.content, file);
        }
    }
}

到此完成。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容