GATEWAY网关上传文件问题

​ gateway网关上传文件,MultipartFile在接口中无法解析到,所以需要把要上传的文件进行Base64编码,通过json格式传给后台。

解析前端传的Base64数据

1、自定义File类

继承MultipartFile类

import org.springframework.web.multipart.MultipartFile;

import java.io.*;

/**
 * base64 转 MultipartFile
 *
 * @author PCCW
 */
public class MyMultipartFile implements MultipartFile {

    private final byte[] imgContent;
    private final String header;

    public Base64DecodedMultipartFile(byte[] imgContent, String header) {
        this.imgContent = imgContent;
        this.header = header.split(";")[0];
    }

    @Override
    public String getName() {
        return System.currentTimeMillis() + Math.random() + "." + header.split("/")[1];
    }

    @Override
    public String getOriginalFilename() {
        return System.currentTimeMillis() + (int) (Math.random() * 10000) + "." + header.split("/")[1];
    }

    @Override
    public String getContentType() {
        return header.split(":")[1];
    }

    @Override
    public boolean isEmpty() {
        return imgContent == null || imgContent.length == 0;
    }

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

    @Override
    public byte[] getBytes() {
        return imgContent;
    }

    @Override
    public InputStream getInputStream() {
        return new ByteArrayInputStream(imgContent);
    }

    @Override
    public void transferTo(File dest) throws IOException {
        try (FileOutputStream outputStream = new FileOutputStream(dest)) {
            outputStream.write(imgContent);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


2、解析Base64数据

解析Base64工具类

import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import java.io.*;

/**
 * base64 转 MultipartFile
 *
 * @author PCCW
 */
public class MultipartFileUtils {

    /**
     * base64转MultipartFile
     * @param base64
     * @return
     */
    public static MultipartFile base64ToMultipart(String base64) {
        try {
            String[] baseStrs = base64.split(",");
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] b;
            b = decoder.decodeBuffer(baseStrs[1]);
            for(int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            return new MyMultipartFile(b, baseStrs[0]);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}

参考:https://www.jianshu.com/p/0ee9b1a3b3e0

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐