|
| 1 | +package com.baeldung.springmvcforms.controller; |
| 2 | + |
| 3 | +import java.io.File; |
| 4 | +import java.io.FileOutputStream; |
| 5 | +import java.io.IOException; |
| 6 | +import java.io.InputStream; |
| 7 | +import javax.servlet.http.HttpServletRequest; |
| 8 | +import javax.servlet.http.HttpServletResponse; |
| 9 | +import org.springframework.stereotype.Controller; |
| 10 | +import org.springframework.web.bind.annotation.RequestMapping; |
| 11 | +import org.springframework.web.bind.annotation.RequestMethod; |
| 12 | +import org.springframework.web.multipart.MaxUploadSizeExceededException; |
| 13 | +import org.springframework.web.multipart.MultipartFile; |
| 14 | +import org.springframework.web.servlet.HandlerExceptionResolver; |
| 15 | +import org.springframework.web.servlet.ModelAndView; |
| 16 | + |
| 17 | +@Controller |
| 18 | +public class FileUploadController implements HandlerExceptionResolver { |
| 19 | + |
| 20 | + @RequestMapping(value = "/uploadFile", method = RequestMethod.GET) |
| 21 | + public String getImageView() { |
| 22 | + return "file"; |
| 23 | + } |
| 24 | + |
| 25 | + @RequestMapping(value = "/uploadFile", method = RequestMethod.POST) |
| 26 | + public ModelAndView uploadFile(MultipartFile file) throws IOException{ |
| 27 | + ModelAndView modelAndView = new ModelAndView("file"); |
| 28 | + |
| 29 | + InputStream in = file.getInputStream(); |
| 30 | + File currDir = new File("."); |
| 31 | + String path = currDir.getAbsolutePath(); |
| 32 | + FileOutputStream f = new FileOutputStream(path.substring(0, path.length()-1)+ file.getOriginalFilename()); |
| 33 | + int ch = 0; |
| 34 | + while ((ch = in.read()) != -1) { |
| 35 | + f.write(ch); |
| 36 | + } |
| 37 | + f.flush(); |
| 38 | + f.close(); |
| 39 | + |
| 40 | + modelAndView.getModel().put("message", "File uploaded successfully!"); |
| 41 | + return modelAndView; |
| 42 | + } |
| 43 | + |
| 44 | + @Override |
| 45 | + public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object object, Exception exc) { |
| 46 | + ModelAndView modelAndView = new ModelAndView("file"); |
| 47 | + if (exc instanceof MaxUploadSizeExceededException) { |
| 48 | + modelAndView.getModel().put("message", "File size exceeds limit!"); |
| 49 | + } |
| 50 | + return modelAndView; |
| 51 | + } |
| 52 | +} |
0 commit comments