Home > OS >  update profile image functionality is not working while hosting as jar
update profile image functionality is not working while hosting as jar

Time:03-03

Hi I am new to Springboot I was trying to develop a application, One of its functionality is to upload profile Image. It was working fine in STS but when I pack it in jar and hosting it on AWS EC2 envirnment I am getting some error while processing that image

Error:

enter image description here

handler for profile picture:

@PostMapping("/process-contact")
    public String processContact(@ModelAttribute Contact contact, @RequestParam("profileImage") MultipartFile file,
            HttpSession session) {

        try {

            contact.setUser(user);
            user.getContacts().add(contact);
            // processing and uploading photo

            if (file.isEmpty()) {
                System.out.println("File is empty");
                contact.setImage("contact.png");

            } else {
                
                //Processing Image
                InputStream inputStream = file.getInputStream();
                Path paths = Paths.get(new ClassPathResource("/static/img").getFile().getPath() "/"  file.getOriginalFilename());
                
                Files.copy(inputStream, paths, StandardCopyOption.REPLACE_EXISTING);
                contact.setImage(file.getOriginalFilename());
                
            }
            
            // Success Message
            session.setAttribute("message", new Message("Your contact is added...", "success"));
            
            this.userRepository.save(user);
            System.out.println("Successfully Added");
        } catch (Exception E) {
            E.printStackTrace();

            // Failed message
            session.setAttribute("message", new Message("Something went wrong " E.getMessage(), "danger"));
        }

        return "normal/add_contact_form";
    }

It is working fine in IDE after some research I found way of writing data in jar is diffrent could some please help me how can I implemenr it for jar also.

Thankyou

CodePudding user response:

all you need to do is replace this line:

Path paths = Paths.get(new ClassPathResource("/static/img").getFile().getPath() "/"  file.getOriginalFilename());

With:

Path paths = Paths.get(new FileSystemResource("/static/img").getFile().getPath() "/"  file.getOriginalFilename());

THat will work like charm.

  • Related