LardaX

Profile Picture Upload

Dec 17th, 2016
340
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.24 KB | None | 0 0
  1. @PostMapping("/{id}/profile-picture/upload")
  2.     @PreAuthorize("isAuthenticated()")
  3.     public String uploadPicture(@PathVariable Integer id, FileBindingModel fileBindingModel) {
  4.         if (!this.userRepository.exists(id)) {
  5.             return "redirect:/profile";
  6.         }
  7.  
  8.         UserDetails principal = (UserDetails) SecurityContextHolder.getContext()
  9.                 .getAuthentication().getPrincipal();
  10.  
  11.         User loggedUser = this.userRepository.findByEmail(principal.getUsername());
  12.  
  13.         User user = this.userRepository.findOne(id);
  14.  
  15.         if (!loggedUser.equals(user)) {
  16.             return "redirect:/login";
  17.         }
  18.  
  19.         MultipartFile file = fileBindingModel.getPicture();
  20.  
  21.         if (file != null) {
  22.  
  23.             String originalFileName = file.getOriginalFilename();
  24.  
  25.             File imageFile = new File
  26.                     ("D:\\javaBroadcast\\newsWebsiteProject\\blog\\src\\main\\resources\\static\\images\\", originalFileName);
  27.  
  28.             try {
  29.                 file.transferTo(imageFile);
  30.                 user.setImagePath(imageFile.getPath());
  31.  
  32.                 this.userRepository.saveAndFlush(user);
  33.  
  34.             } catch (IOException e) {
  35.                 e.printStackTrace();
  36.             }
  37.         }
Advertisement
Add Comment
Please, Sign In to add comment