I want to save uploaded images to a specific folder in a Spring 3 MVC application deployed on Tomcat
My problem is that I cannot save the uploaded images files to the host where the appliciation is running.
Here is what I tried:
private void saveFile(MultipartFile multipartFile, int id) throws Exception { String destination = "/images/" + id + "/" + multipartFile.getOriginalFilename(); File file = new File(destination); multipartFile.transferTo(file); }
Result: FileNotFoundException - Yes sure, I do want create this file!?!
I tried it using the context.getRealPath
or getResources("destination")
, but without any success.
How can I create a new file in a specific folder of my app with the content of my multipart file?
A new attribute "maxSwallowSize" is the key to deal this situation. It should happen when you upload a file which is larger than 2M. Because the 2M is the default value of this new attribute .
Spring Boot file uploader Create a Spring @Controller class; Add a method to the controller class which takes Spring's MultipartFile as an argument; Save the uploaded file to a directory on the server; and. Send a response code to the client indicating the Spring file upload was successful.
This code will surely help you.
String filePath = request.getServletContext().getRealPath("/"); multipartFile.transferTo(new File(filePath));
Let's create the uploads directory in webapp and save files in webapp/uploads:
@RestController public class GreetingController { private final static Logger log = LoggerFactory.getLogger(GreetingController.class); @Autowired private HttpServletRequest request; @RequestMapping(value = "/uploadfile", method = RequestMethod.POST) public @ResponseBody ResponseEntity handleFileUpload(@RequestParam("file") MultipartFile file) { if (!file.isEmpty()) { try { String uploadsDir = "/uploads/"; String realPathtoUploads = request.getServletContext().getRealPath(uploadsDir); if(! new File(realPathtoUploads).exists()) { new File(realPathtoUploads).mkdir(); } log.info("realPathtoUploads = {}", realPathtoUploads); String orgName = file.getOriginalFilename(); String filePath = realPathtoUploads + orgName; File dest = new File(filePath); file.transferTo(dest);
the codeString realPathtoUploads = request.getServletContext().getRealPath(uploadsDir);
returns me next path if I run the app from Idea IDEC:\Users\Iuliia\IdeaProjects\ENumbersBackend\src\main\webapp\uploads\
and next path if I make .war and run it under Tomcat:D:\Programs_Files\apache-tomcat-8.0.27\webapps\enumbservice-0.2.0\uploads\
My project structure:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With