将二进制文件流转化为MockMultipartFile 文件

1.引入spring依赖

        //引入spring-test依赖
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.3.8</version>
        </dependency>

2.写方法

private String extracted(byte[] data) {
    //创建缓存输出流
        BufferedOutputStream bos = null;
    //  FileOutputStream流是指文件字节输出流,专用于输出原始字节流如图像数据等,其继承OutputStream类,拥有输出流的基本特性
        FileOutputStream fos = null;
    //创建文件对象
        File file = null;
        String fileName1 = "1.png";
        String filePath = System.getProperty("user.dir") + File.separator + File.separator;
        try {
            File file1 = new File(filePath);
            if (!file1.exists() && file1.isDirectory()) {
                file1.mkdirs();
            }
        // file 进行赋值
            file = new File(filePath + "\\" + fileName1);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
        //将data写入文件中
            bos.write(data);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        //创建 MockMultipartFile 对象 MockMultipartFile implements MultipartFile
        MockMultipartFile mockMultipartFile = null;
        try {
        //将本地的文件 转换为输出流 进行 转格式
            FileInputStream inputStream = new FileInputStream(file);
       //通过 MockMultipartFile 带参构造进行 创建对象 及赋值
            mockMultipartFile = new MockMultipartFile(file.getName(), file.getName(), ContentType.APPLICATION_OCTET_STREAM.toString(),
                    inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
  • 20
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 29
    评论
评论 29
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

guicai_guojia

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值