MultipartFile、File、base64三者的相互转换的工具类及使用说明

1.File

1.1 File转base64


 /**
     * File转base64
     * @param filePath 文件路径
     * @return
     */
    private static String fileToBase64(String filePath){
        byte[] b = new byte[0];
        try {
            b = Files.readAllBytes(Paths.get(filePath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Base64.getEncoder().encodeToString(b);
    }

1.2 File转MultipartFile

/**
     * File转MultipartFile
     * @param filePath 文件路径
     * @return
     * @throws IOException
     */
    public static MultipartFile fileToMultipartFile(String filePath) {
        File file = new File(filePath);
        FileInputStream input = null;
        MultipartFile multipartFile = null;
        try {
            input = new FileInputStream(file);
            multipartFile = new MockMultipartFile("file",
                    file.getName(), "text/plain", input);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return multipartFile;
    }

2. base64

2.1 base64转MultipartFile

/**
     * base64转MultipartFile
     * @param base64String base64字符串
     * @param fileName 文件名称
     * @return
     * @throws IOException
     */
    private static MultipartFile base64ToMultipartFile(String base64String, String fileName) {
        // 解码base64字符串 (如果base64有前缀如:data:image/jpg;base64,则需要去掉前缀,我这里有前缀,所以需要去掉)
        //有前缀
        byte[] decode = Base64.getDecoder().decode(base64String.split(",")[1]);
        //无前缀
//        byte[] decode = Base64.getDecoder().decode(base64String);
        // 创建字符串
        String name = fileName +  ".png"; // 假设文件名
        String contentType = "image/png"; // 假设内容类型
        return new MockMultipartFile(fileName, name, contentType, decode);
    }

2.2 base64转File

/**
     * base64转File
     * @param base64
     * @param filePath
     */
    private static void base64ToFile(String base64, String filePath){
        File file = new File(filePath);
        //去掉前缀
        byte[] decodedBytes = Base64.getDecoder().decode(base64.split(",")[1]);
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
            fos.write(decodedBytes);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println("创建成功");
    }

3.MultipartFile

3.1 MultipartFile转base64


    /**
     * MultipartFile转base64
     * @param file
     * @return
     */
    public static String multipartFileToBase64(MultipartFile file) {
        byte[] fileBytes = new byte[0];
        try {
            fileBytes = file.getBytes();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String base64String = Base64.getEncoder().encodeToString(fileBytes);
        return base64String;
    }

3.2 multipartFile转File

 /**
     * multipartFile转File
     * @param multipartFile
     * @return
     */
    public static File multipartFileToFile(MultipartFile multipartFile) {
        //文件上传前的名称
        String fileName = multipartFile.getOriginalFilename();
        File file = new File(fileName);
        OutputStream out = null;
        try{
            //获取文件流,以文件流的方式输出到新文件
//    InputStream in = multipartFile.getInputStream();
            out = new FileOutputStream(file);
            byte[] ss = multipartFile.getBytes();
            for(int i = 0; i < ss.length; i++){
                out.write(ss[i]);
            }
        }catch(IOException e){
            e.printStackTrace();
        }finally {
            if (out != null){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        //注意:这时候,系统会在根目录下创建一个临时文件,这个临时文件并不是我们需要的,所以文件处理完成之后,需要将其删除。
        // 操作完上的文件 需要删除在根目录下生成的文件
        File f = new File(file.toURI());
        if (f.delete()){
            System.out.println("删除成功");
        }else {
            System.out.println("删除失败");
        }
        return file;
    }

4. 完整代码及示例

import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

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

public class Main {


    public static void main(String[] args) {
        String filePath = "E:/test/test1.png";
        // base64
        System.out.println(fileToBase64(filePath));
        //如果是图片: 如果前端想要直接通过base64能够预览,或者浏览器直接打开,需要添加前缀
        String base64String =  "data:image/jpg;base64," + fileToBase64(filePath);
        System.out.println(base64String);

        //base64 转MultipartFile
        MultipartFile multipartFile = base64ToMultipartFile(base64String, "测试");

        //base64 转File
        base64ToFile(base64String, "E:/test/test2.png");

        multipartFileToFile(multipartFile);
    }

    /**
     * File转base64
     * @param filePath 文件路径
     * @return
     */
    private static String fileToBase64(String filePath){
        byte[] b = new byte[0];
        try {
            b = Files.readAllBytes(Paths.get(filePath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Base64.getEncoder().encodeToString(b);
    }

    /**
     * File转MultipartFile
     * @param filePath 文件路径
     * @return
     * @throws IOException
     */
    public static MultipartFile fileToMultipartFile(String filePath) {
        File file = new File(filePath);
        FileInputStream input = null;
        MultipartFile multipartFile = null;
        try {
            input = new FileInputStream(file);
            multipartFile = new MockMultipartFile("file",
                    file.getName(), "text/plain", input);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return multipartFile;
    }


    /**
     * base64转MultipartFile
     * @param base64String base64字符串
     * @param fileName 文件名称
     * @return
     * @throws IOException
     */
    private static MultipartFile base64ToMultipartFile(String base64String, String fileName) {
        // 解码base64字符串 (如果base64有前缀如:data:image/jpg;base64,则需要去掉前缀,我这里有前缀,所以需要去掉)
        //有前缀
        byte[] decode = Base64.getDecoder().decode(base64String.split(",")[1]);
        //无前缀
//        byte[] decode = Base64.getDecoder().decode(base64String);
        // 创建字符串
        String name = fileName +  ".png"; // 假设文件名
        String contentType = "image/png"; // 假设内容类型
        return new MockMultipartFile(fileName, name, contentType, decode);
    }


    /**
     * base64转File
     * @param base64
     * @param filePath
     */
    private static void base64ToFile(String base64, String filePath){
        File file = new File(filePath);
        //去掉前缀
        byte[] decodedBytes = Base64.getDecoder().decode(base64.split(",")[1]);
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
            fos.write(decodedBytes);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println("创建成功");
    }

    /**
     * MultipartFile转base64
     * @param file
     * @return
     */
    public static String multipartFileToBase64(MultipartFile file) {
        byte[] fileBytes = new byte[0];
        try {
            fileBytes = file.getBytes();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String base64String = Base64.getEncoder().encodeToString(fileBytes);
        return base64String;
    }

    /**
     * multipartFile转File
     * @param multipartFile
     * @return
     */
    public static File multipartFileToFile(MultipartFile multipartFile) {
        //文件上传前的名称
        String fileName = multipartFile.getOriginalFilename();
        File file = new File(fileName);
        OutputStream out = null;
        try{
            //获取文件流,以文件流的方式输出到新文件
//    InputStream in = multipartFile.getInputStream();
            out = new FileOutputStream(file);
            byte[] ss = multipartFile.getBytes();
            for(int i = 0; i < ss.length; i++){
                out.write(ss[i]);
            }
        }catch(IOException e){
            e.printStackTrace();
        }finally {
            if (out != null){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        //注意:这时候,系统会在根目录下创建一个临时文件,这个临时文件并不是我们需要的,所以文件处理完成之后,需要将其删除。
        // 操作完上的文件 需要删除在根目录下生成的文件
        File f = new File(file.toURI());
        if (f.delete()){
            System.out.println("删除成功");
        }else {
            System.out.println("删除失败");
        }
        return file;
    }

}

5. 前端el-upload 数据处理

请看博客链接 https://blog.csdn.net/qq_45774406/article/details/137473599?spm=1001.2014.3001.5501

人只要有一种向上的精神,朝着自己的目标一步步努力,成功的机会就会越来越大。是块金子,无论在哪,总是会发光的!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值