simslay simslay - 2 years ago 115
Java Question

How to upload images in src/main/webapp/resources with spring MVC

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 :

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

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
to have an absolute path of my system like this :

Answer Source

I would say it is not good idea. In fact src folder does not exist. The resources are moved on compile.

Moreover it's not good to place uploaded under web root. First because on restart the web root could be replaced with a new structure from WAR and because of security reasons. You get a potential hole letting something to be uploaded in the place where it could be run.

Instead define an upload path property and use it to store uploaded files and download them if necessary.


private String upload;

and specify property in e.g. or as JVM argument on start

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download