0

I have uploaded an image in tomcat temp folder using this code:

@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
public @ResponseBody
String uploadFileHandler(@RequestParam("name") String name,
        @RequestParam("file") MultipartFile file) {

    if (!file.isEmpty()) {
        try {
            byte[] bytes = file.getBytes();

            // Creating the directory to store file
            String rootPath = System.getProperty("catalina.home");
            File dir = new File(rootPath + File.separator + "tmpFiles");
            if (!dir.exists())
                dir.mkdirs();

            // Create the file on server
            File serverFile = new File(dir.getAbsolutePath()
                    + File.separator + name);
            BufferedOutputStream stream = new BufferedOutputStream(
                    new FileOutputStream(serverFile));
            stream.write(bytes);
            stream.close();
            System.out.println(serverFile.getAbsolutePath());

            logger.info("Server File Location="
                    + serverFile.getAbsolutePath());

            return "You successfully uploaded file=" + name;
        } catch (Exception e) {
            return "You failed to upload " + name + " => " + e.getMessage();
        }
    } else {
        return "You failed to upload " + name
                + " because the file was empty.";
    }
}

Now I would like to access that image in to jsp page. I tried in this way:

<img src="/home/sudeepcv/java work place/Server/apache-tomcat-7.0.54/tmpFiles/img.jpg" width="100%" />

but it is not loading. How can I access this by relative path?

vvvvv
  • 25,404
  • 19
  • 49
  • 81
sudeep cv
  • 1,017
  • 7
  • 20
  • 34

1 Answers1

0

You cannot serve files outside of your webapp, you will need to read the image again and send it as base64 encoded data, see this question for how you can do it and for browser support.

But I would recommend that you put images you upload in some directory our webapp can access, for example <your-app>/images and use <img src="images/img.jpg" width="100%" /> in your HTML.

To know the path of you application you could use ServletContext#getRealPath instead of System.getProperty("catalina.home"):

String rootPath = context.getRealPath(""); // need access to the ServletContext

Although this is a way to do it, you need to know that servlet containers may be configured to not unpack war files, in which case getRealPath will not be usefull.

Community
  • 1
  • 1
A4L
  • 17,353
  • 6
  • 49
  • 70