Upload large files : Spring Boot

So guys, I was dealing with a problem recently. I was getting OutOfMemoryError when trying to upload and save large files (like 2/3 gbs). I was trying to deal it with HttpServletRequest but didn’t end so well. But after spending some time thinking about the universe, mens style, water pond (road? seriously?!!) on dhaka city after a heavy rain and how to make life easier doing absolutely nothing, figured out the nicest way to do it.

We’ll use apache commons IO to copy inputstream (and write) to a file. But it has nothing to do with OutOfMemoryError. It’s just a convenient and simple way to write inputstream to a file

1. Dependency


2. Create a multipart form

            <form th:action="@{/admin/categories/create}" method="post" enctype="multipart/form-data">

                <div id="file_upload">
                    <div class="form-group">
                        <input name="image" id="image" class="form-control" type="file"></input>

                <input type="submit" value="UPLOAD"></input>

3. Controller

    @RequestMapping(value = "/create", method = RequestMethod.POST)
    private String create(@RequestParam("image") MultipartFile multipartFile) throws IOException{
           * Don't do this.
           * it loads all of the bytes in java heap memory that leads to OutOfMemoryError. We'll use stream instead. 
        // byte[] fileBytes = multipartFile.getBytes(); 
        InputStream fileStream = multipartFile.getInputStream();
        File targetFile = new File("src/main/resources/targetFile.tmp");
        FileUtils.copyInputStreamToFile(fileStream, targetFile);
        return "redirect:/?message=Successful!";

Nice. Everything should be alright and your file should stay in right place without braking of corrupting your data.

Leave a Reply

Your email address will not be published. Required fields are marked *