Morteza Asadi
Morteza Asadi

Reputation: 1855

upload large file in spring using FileCopyUtils.copy

I'm using org.springframework.util.FileCopyUtils to upload files in my projects.

FileCopyUtils.copy(multipartFile.getBytes(), new FileOutputStream( basePath + "/" + uploadedfile.getFileName()));

It use a FileOutputStream for uploading file and for smaller file this work fine, But how I can upload file with 2GB size or higher?

Upvotes: 0

Views: 3272

Answers (2)

Morteza Asadi
Morteza Asadi

Reputation: 1855

According the @m-deinum's comment, I Finally use org.springframework.util.StreamUtils to upload large files:

StreamUtils.copy(multipartFile.getInputStream(), new FileOutputStream( basePath + "/" + uploadedfile.getFileName()));

I use an input stream instead of a byte[] for uploading files, also for read (downloading) files I use InputStream:

try {
        inputStream = new FileInputStream(basePath + "/" + fileName);
        byte[] buffer = new byte[4096];
        int bytesRead = 0;
        do {
            bytesRead = inputStream.read(buffer, 0, buffer.length);
            httpServletResponse.getOutputStream().write(buffer, 0, bytesRead);
        } while (bytesRead == buffer.length);

        /* some code for set attributes to httpServletResponse */
    } finally {
        if (inputStream != null)
            inputStream.close();
    }

Upvotes: 1

Colin Shah
Colin Shah

Reputation: 165

This may help :

1st thing we have to check is -

multipartResolver maxUploadSize: maximum upload size for a single request. That means the total size of all upload files cannot exceed this configured maximum. Default is unlimited (value of -1).

2nd thing we have to check is -

which server you are using to run your application?

If it is tomcat then, you have to do some configuration in it

Refer : https://tomcat.apache.org/tomcat-7.0-doc/config/http.html

maxPostSize

The maximum size in bytes of the POST which will be handled by the container FORM URL parameter parsing. The limit can be disabled by setting this attribute to a value less than or equal to 0. If not specified, this attribute is set to 2097152 (2 megabytes).

Another Limit is:

maxHttpHeaderSize The maximum size of the request and response HTTP header, specified in bytes. If not specified, this attribute is set to 4096 (4 KB).

You find them in

$TOMCAT_HOME/conf/server.xml

<Connector port="8080" protocol="HTTP/1.1"
           connectionTimeout="20000"
           maxPostSize="4294967296"
           redirectPort="8443" />

This will set the maximum file upload size to 4GB.

Upvotes: 1

Related Questions