将 InputStream 流转成 MultipartFile

2023-10-31

MultipartFile是一个接口, 有一个MockMultipartFile实现类,里面有构造方法可以直接将输入流转为MutipartFile对象:

MultipartFile File = new MockMultipartFile(filename, file.getName(), file.getContentType(), fileStream);

使用MockMultipartFile类, 项目需要导入org.springframework:spring-test:5.1.2.RELEASE依赖, 可能会存在不方便的地方. 另外一种还可以自定义一个类去实现MultipartFile接口, 然后将MockMultipartFile类中的内容复制过来就行了.  主要工作就是将输入流转换为byte数组的过程FileCopyUtils.copyToByteArray(contentStream)).    往里面查看就是输入流转为输出流, 然后输出流.toByteArray()的过程

  public HzMultipartFile(String name, @Nullable String originalFilename, @Nullable String contentType, @Nullable byte[] content) {
        Assert.hasLength(name, "Name must not be null");
        this.name = name;
        this.originalFilename = originalFilename != null ? originalFilename : "";
        this.contentType = contentType;
        this.content = content != null ? content : new byte[0];
    }

    public HzMultipartFile(String name, @Nullable String originalFilename, @Nullable String contentType, InputStream contentStream) throws IOException {
        this(name, originalFilename, contentType, FileCopyUtils.copyToByteArray(contentStream));
    }


 FileCopyUtils.class
 public static byte[] copyToByteArray(@Nullable InputStream in) throws IOException {
        if (in == null) {
            return new byte[0];
        } else {
            ByteArrayOutputStream out = new ByteArrayOutputStream(4096);
            copy((InputStream)in, (OutputStream)out);
            return out.toByteArray();
        }
    }



    StreamUtils.class
    public static int copy(InputStream in, OutputStream out) throws IOException {
        Assert.notNull(in, "No InputStream specified");
        Assert.notNull(out, "No OutputStream specified");
        int byteCount = 0;
        byte[] buffer = new byte[4096];

        int bytesRead;
        for(boolean var4 = true; (bytesRead = in.read(buffer)) != -1; byteCount += bytesRead) {
            out.write(buffer, 0, bytesRead);
        }

        out.flush();
        return byteCount;
    }

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将 InputStream 流转成 MultipartFile 的相关文章

随机推荐