【Java】如何将二进制转换成MultipartFile

        业务场景:前端发送请求到后端进行文件上传,后端接收文件并调用第三方接口进行文件处理,响应格式为二进制,然后我们需要将二进制进行转换为MultipartFile进行文件上传。

        如果你想要将File转换成MultipartFile,可以参考:【Java】如何将File转换成MultipartFile_java file 转multipartfile_MXin5的博客-CSDN博客

 1.传递二进制responseBytes和file的名称即可。

// responseBytes为二进制流,file.getOriginalFilename()为文件的名称。
ByteArrayMultipartFile responseFile = new ByteArrayMultipartFile(responseBytes, "file", file.getOriginalFilename(), "application/octet-stream");

2. 将二进制流转换成MultipartFile的类:


import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import java.nio.file.CopyOption;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;

/**
 * 将二进制流转换成MultipartFile类的对象
 */
public class ByteArrayMultipartFile implements MultipartFile {

    private final byte[] content;
    private final String name;
    private final String originalFilename;
    private final String contentType;

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

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

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

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

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

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

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

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

    @Override
    public void transferTo(File dest) throws IOException, IllegalStateException {
        Files.copy(new ByteArrayInputStream(content), dest.toPath(), new CopyOption[]{StandardCopyOption.REPLACE_EXISTING});
    }

    @Override
    public void transferTo(Path dest) throws IOException, IllegalStateException {
        Files.copy(new ByteArrayInputStream(content), dest, new CopyOption[]{StandardCopyOption.REPLACE_EXISTING});
    }
}

直接使用

你可能感兴趣的:(Java,java,开发语言)