I'm trying to upload an image with spring MVC in src/main/webapp/resources to display it in an img tag (<img src="<c:url value="/resources/images/image.jpg" />" alt="image" />
) in my jsp. I have this controller :
@Controller
public class FileUploadController implements ServletContextAware {
private ServletContext servletContext;
private String rootPath;
@RequestMapping(value = "/uploadSingleFile", method = RequestMethod.GET)
public ModelAndView uploadSingleFileFormDisplay() {
return new ModelAndView("uploadSingleFile");
}
@RequestMapping(value = "/uploadSingleFile", method = RequestMethod.POST)
public @ResponseBody String uploadSingleFileHandler(@RequestParam("file") MultipartFile file) {
String filename = file.getOriginalFilename();
rootPath = servletContext.getRealPath("/") + "resources/uploads";
if (!file.isEmpty()) {
try {
Document document = new Document();
Image image = new Image();
byte[] bytes = file.getBytes();
BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(
rootPath + "/" + filename
)));
stream.write(bytes);
stream.close();
return "You successfully uploaded " + filename + "!";
} catch (Exception e) {
return "You failed to upload " + filename + " => " + e.getMessage();
}
} else {
return "You failed to upload " + filename + " because the file was empty.";
}
}
(...)
}
How do I build the rootPath
to have an absolute path of my system like this : C:/absolute/path/to/webapp/resources
or /absolute/path/to/webapp/resources
?