Reputation: 7
i get this error when trying to upload an image to a dir:
Failed to complete request: java.lang.RuntimeException: java.io.IOException: java.io.FileNotFoundException: C:\Users\LANDRY\AppData\Local\Temp\tomcat.8080.7917247661488050367\work\Tomcat\localhost\ROOT\uploads\profile-pictures\Abraham8\71_4de0ea79-7b60-466a-8df1-0c4266cacb5e.jpg (The system cannot find the path specified).
meanwhile here is the method:
private static final String UPLOAD_DIR = "/uploads/profile-pictures/";;
private static final long MAX_FILE_SIZE = 2 * 1024 * 1024; // 2MB
@Override
public void uploadProfilePicture(User curUser, MultipartFile file){
String contentType = file.getContentType();
assert contentType != null;
if(contentType.equals("jpg") || contentType.equals("png")){
throw new IllegalArgumentException("Invalid file type. Only jpeg and png are allowed");
}
System.out.println("after first condition");
if(file.getSize() > MAX_FILE_SIZE){
throw new IllegalArgumentException("File size exceeds the maximum allowed size (2MB)");
}
System.out.println("after second condition");
String fileName = null;
try {
if (curUser.getProfilePicturePath() != null) {
Path oldFilePath = Paths.get(curUser.getProfilePicturePath().substring(1)); // Remove the leading "/"
Files.deleteIfExists(oldFilePath);
}
System.out.println("In the try catch block");
String fileExtension = contentType.equals("image/jpeg") ? "jpg" : "png";
fileName = curUser.getId()+"_"+ UUID.randomUUID() +"."+ fileExtension;
Path userUplaodPath = Paths.get(UPLOAD_DIR + curUser.getUsername());
if(!Files.exists(userUplaodPath)){
Files.createDirectories(userUplaodPath);
}
System.out.println("Still there though");
Path filePath = userUplaodPath.resolve(fileName);
file.transferTo(filePath.toFile());
System.out.println("File added to system path");
curUser.setProfilePicturePath("/" + UPLOAD_DIR + curUser.getUsername() + "/" + fileName);
System.out.println("file added the database");
userRepository.save(curUser);
System.out.println("file saved successfully");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
i need help pls
Upvotes: -1
Views: 21
Reputation: 36
You should define a specific location on disk (which already exists) where you can save files. Try not to use relative paths once inside a Servlet container, because there are no guarantees that the underlying file system will always look the same. Then the one deploying the application will need to take care of providing this path. (Makes sense to verify on application startup whether property is set and fail fast if not)
Instead, you should be reading an absolute file location from properties or something along those lines, where uploaded files will be stored, e.g.:
uploaded.files.path=C:\Users\me\tomcat\uploads
And then you can use that property to build an absolute path to the file(s) you want.
Upvotes: 0