Skip to content

Processing large files. #35449

@Dzmitry-yarik

Description

@Dzmitry-yarik

There is a StandardMultipartFile class in Spring.
It has a getBytes method that looks like this:

public byte[] getBytes() throws IOException {
return FileCopyUtils.copyToByteArray(this.part.getInputStream());
}

I have a question. Is this a good approach for large files if I need to get byte[], because transferTo() returns void?

I suggest doing the upload in parts. For example, like this:

public byte[] getBytes(int chunkSize) throws IOException {
    long size = this.part.getSize();
    try (InputStream in = this.part.getInputStream();
         ByteArrayOutputStream baos = new ByteArrayOutputStream((int) size)) {

        byte[] buffer = new byte[chunkSize];
        int bytesRead;
        while ((bytesRead = in.read(buffer)) != -1) {
            baos.write(buffer, 0, bytesRead);
        }
        return baos.toByteArray();
    }
}

This is not an ideal option, just as an idea.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions