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
<dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.5</version> </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"> <h4>Image</h4> <input name="image" id="image" class="form-control" type="file"></input> </div> <input type="submit" value="UPLOAD"></input> </form>
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.
I conceive you have mentioned some very interesting points, thanks for the post.
I’m really loving the theme/design of your website. Do you ever run into any web browser compatibility issues? A couple of my blog readers have complained about my site not operating correctly in Explorer but looks great in Firefox. Do you have any recommendations to help fix this problem?|
Great post. I was checking constantly this weblog and I am impressed! Extremely useful information particularly the final part 🙂 I maintain such info much. I was seeking this particular info for a very lengthy time. Thanks and good luck. |
Every weekend i used to go to see this site, for the reason that i wish for enjoyment, as this this web page conations truly fastidious funny stuff too.|