In my current spring, some forms have a field where the user can upload a file, which should be saves inside the folder resources
from project (src/main/resources, following the structure created by maven).
the method responsible for save the file in this folder is working ok until this line:
URL path = this.getClass().getClassLoader().getResource(file);
the variable path
is staying with the value null
. the variable file
is defined with this value:
String file = "/"+this.getName()+"/"+String.valueOf(id)+"/picture.jpg";
Anyone can tell me the right way to do this?
PS.: the complete code for this method is:
public boolean upload_picture(E e, MultipartFile f) {
Integer id = null;
if(f == null) {
return false;
}
Class<?> clazz = e.getClass();
Method methods[] = clazz.getDeclaredMethods();
for(int i=0; i<methods.length; i++) {
if(methods[i].getName().equals("getId")) {
try {
id = (Integer) methods[i].invoke(e);
} catch (IllegalAccessException e1) {
e1.printStackTrace();
return false;
} catch (IllegalArgumentException e1) {
e1.printStackTrace();
return false;
} catch (InvocationTargetException e1) {
e1.printStackTrace();
return false;
}
}
}
BufferedImage src;
try {
src = ImageIO.read(new ByteArrayInputStream(f.getBytes()));
} catch (IOException e3) {
e3.printStackTrace();
return false;
}
String file = "/"+this.getName()+"/"+String.valueOf(id)+"/picture.jpg";
URL path = this.getClass().getClassLoader().getResource(file);
File destination;
try {
destination = new File(path.toURI());
} catch (URISyntaxException e2) {
destination = new File(path.getPath());
e2.printStackTrace();
}
try {
ImageIO.write(src, "jpeg", destination);
return true;
} catch (IOException e1) {
e1.printStackTrace();
return false;
}
}