Blogs Hub

by AskGif | Aug 30, 2018 | Category :coding

How can I upload image using spring MVC, Java?

How can I upload image using spring MVC, Java?

<p>This is a Generic Java Controller Written to Upload an Image to any Specific Folder in Spring MVC Application. You can use the below code in your application if you want to use functionality to upload an image to any particular folder in Spring MVC Application.</p> <pre class="language-java"><code>package net.askgif.spring3.controller; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletRequest; import net.askgif.spring3.form.FileUploadForm; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.multipart.MultipartFile; @Controller public class FileUploadController { //private String saveDirectory = "D:/Test/Upload/"; //Here I Added private String saveDirectory = null; //Here I Added @RequestMapping(value = "/show", method = RequestMethod.GET) public String displayForm() { return "file_upload_form"; } @SuppressWarnings("null") @RequestMapping(value = "/save", method = RequestMethod.POST) public String save( @ModelAttribute("uploadForm") FileUploadForm uploadForm, Model map,HttpServletRequest request) throws IllegalStateException, IOException{ List&lt;MultipartFile&gt; files = uploadForm.getFiles(); List&lt;String&gt; fileUrl = new ArrayList&lt;String&gt;();; String fileName2 = null; fileName2 = request.getSession().getServletContext().getRealPath("/"); saveDirectory = fileName2+"images\\"; List&lt;String&gt; fileNames = new ArrayList&lt;String&gt;(); //System.out.println("user directory : "+System.getProperty("user.dir")); System.out.println("applied directory : " + saveDirectory); if(null != files &amp;&amp; files.size() &gt; 0) { for (MultipartFile multipartFile : files) { String fileName = multipartFile.getOriginalFilename(); System.out.println("applied directory : " + saveDirectory+fileName); if(!"".equalsIgnoreCase(fileName)){ //Handle file content - multipartFile.getInputStream() fileUrl.add(new String(saveDirectory + fileName)); multipartFile.transferTo(new File(saveDirectory + fileName)); //Here I Added fileNames.add(fileName); } //fileNames.add(fileName); //Handle file content - multipartFile.getInputStream() //multipartFile.transferTo(new File(saveDirectory + multipartFile.getOriginalFilename())); //Here I Added } } map.addAttribute("files", fileNames); map.addAttribute("imageurl",fileUrl); return "file_upload_success"; } }</code></pre> <p>&nbsp;</p> <p>&nbsp;</p>

read more...