Base64编码转MultipartFile工具类

1,480 阅读1分钟

Base64编码转MultipartFile工具类

开发中遇到base64文件需要上传到mino中,尝试了很多转的实现方法都不行,这一版经过6000多条数据测试没有问题

private final byte[] fileContent;

private final String extension;
private final String contentType;


public Base64ToMultipartFile(String base64, String dataUri) {
    this.fileContent = Base64.getDecoder().decode(base64.getBytes(StandardCharsets.UTF_8));
    this.extension = dataUri.split(";")[0].split("/")[1];
    this.contentType = dataUri.split(";")[0].split(":")[1];
}

public Base64ToMultipartFile(String base64, String extension, String contentType) {
    this.fileContent = Base64.getDecoder().decode(base64.getBytes(StandardCharsets.UTF_8));
    this.extension = extension;
    this.contentType = contentType;
}

@Override
public String getName() {
    return "param_" + System.currentTimeMillis();
}

@Override
public String getOriginalFilename() {
    return "file_" + System.currentTimeMillis() + "." + extension;
}

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

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

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

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

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

@Override
public void transferTo(File file) throws IOException, IllegalStateException {
    try (FileOutputStream fos = new FileOutputStream(file)) {
        fos.write(fileContent);
    }
}