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

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

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

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

java 复制代码
// responseBytes为二进制流,file.getOriginalFilename()为文件的名称。
ByteArrayMultipartFile responseFile = new ByteArrayMultipartFile(responseBytes, "file", file.getOriginalFilename(), "application/octet-stream");
  1. 将二进制流转换成MultipartFile的类:
java 复制代码
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});
    }
}

直接使用

相关推荐
geovindu1 小时前
python:Logistic Regression
开发语言·后端·python·算法
摇滚侠2 小时前
《On Java 中文版 基础卷》阅读笔记 内部类 21
java·开发语言·笔记
番茄味城市甜菜2 小时前
二叉树刷题(C语言)
c语言·开发语言
布莱克6052 小时前
Swift 自动引用计数(ARC)详解:原理、循环引用与最佳实践
开发语言·ios·swift·arc·自动引用计数
FungLeo2 小时前
FengCMS·PHP+MySQL 升级实录 ·本地容器环境设计:只读挂载、LOCAL_UID、数据卷权限
开发语言·mysql·docker·php·fengcms
geovindu3 小时前
python: Random Forest
开发语言·后端·python·算法·随机森林
真上帝的左手3 小时前
2. 编程语言-Python-Anaconda
开发语言·python
.道阻且长.3 小时前
Linux基础IO:理解文件以及回顾C文件接口
linux·运维·服务器·c语言·开发语言·职场和发展
凌冰_4 小时前
数据结构 - 线性结构(三)
java·数据结构·算法·软件工程
Rain的Java大神之路5 小时前
Spring AI 2.0 GA 深度复盘:Java 后端做 AI 的分水岭,到底画在哪?
java·后端·aigc