0

I follow this approach successfully uploaded to "/var/www/java/Football/src/main/webapp/resources/images" folder but here i need to specify complete path , now question is to get root path directly that is like "webapp/resources/images" no need to specify complete path, how to get root path ?

@RequestMapping(value="/saveDeal",method=RequestMethod.POST)
public String saveDeal(@ModelAttribute("saveDeal") Deal deal,BindingResult result,@RequestParam("couponCode") MultipartFile file,HttpServletRequest request){

    if(!file.isEmpty()){
        try{
            byte[] bytes=file.getBytes();
            System.out.println("Byte Data :"+bytes);
            String fileName=file.getOriginalFilename();
        File newFile = new File("/var/www/java/Football/src/main/webapp/resources/images");

           if (!newFile.exists()){
                newFile.mkdirs();

            }
            File serverFile = new File(newFile.getAbsolutePath()+File.separator+fileName);
            BufferedOutputStream stream = new BufferedOutputStream(
                    new FileOutputStream(serverFile));
            stream.write(bytes);
            stream.close();


        }catch(Exception e){
            e.printStackTrace();
        }
    }

    return "redirect:viewDeals.html";
}

3 Answers 3

1

This works fine try it out....it will return you the entire path

String filePath = "/uploads/filename";

    // get absolute path of the application
    ServletContext context = request.getServletContext();
    String appPath = context.getRealPath("");

OR

String filepath = "/uploads/" + "tenant/" + tenant + "/project/"
                + projectId + "/task/" + taskId;
        String realPathtoFetch = request.getServletContext().getRealPath(
                filepath);
Sign up to request clarification or add additional context in comments.

Comments

1

Yes, use ServletContext#getRealPath()

Try this to store Images under "src/main/webapp/resources/profile-pictures":

@RequestMapping(value="/upload", method = RequestMethod.POST)
public String handleFormUpload(@RequestParam("imageFile") MultipartFile file, Principal principal) {

    String webappRoot = servletContext.getRealPath("/");
    String LoggedInUser = principal.getName();
    User user = userService.findLoggedInUser(LoggedInUser);
    try {
        if (!file.isEmpty()) {
             BufferedImage src = ImageIO.read(new ByteArrayInputStream(file.getBytes()));
             //Images will be stored under "src/main/webapp/resources/profile-pictures"
             File destination = new File(webappRoot + "/resources/profile-pictures/ProfileImage"+user.getName()+".jpg"); 
             ImageIO.write(src, "png", destination);
        } 
    } catch (Exception e) {
        System.out.println("Exception occured" + e.getMessage());
        return "redirect:/account/upload?success=false";
    }
    return "redirect:/account/upload?success=true";
}

You can refer the Complete Source Code in this Repository.

1 Comment

In StackOverFlow you show your thanks by clicking Upvote :)
0

I wonder what you mean with the 'root' path. As a servlet, you have no idea what your contextroot is, in what applicationserver that is, and if you're running exploded or in a war (or an EAR). For example, the person running the code might have compiled it in a JAR, which is packaged in a WAR, which is packaged in an EAR. Then there is no actual 'root' of your (compiled) java file, and if there is (if it's exploded on the disk), it will still be read-only.

So I don't think this will ever work. You need to define a directory (possibly configurable) where files will be stored. Let it be injected by a FileResource or something and then the configuration will have to take care to define a proper location. On Unix, that might be /var/user/JavaTempUser/uploads, on windows, that might be e:\uploads. Heck, it might even be JavaOs or something old. As a java programmer, you should be aware that you do NOT know what operating system will be run (hence the File abstractions).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.