I did a little digging on the source code itself to find out why this is happening.
In the class org.springframework.web.multipart.support.StandardMultipartHttpServletRequest
two functions exists
@Override
public void transferTo(File dest) throws IOException, IllegalStateException {
this.part.write(dest.getPath());
if (dest.isAbsolute() && !dest.exists()) {
FileCopyUtils.copy(this.part.getInputStream(), Files.newOutputStream(dest.toPath()));
}
}
@Override
public void transferTo(Path dest) throws IOException, IllegalStateException {
FileCopyUtils.copy(this.part.getInputStream(), Files.newOutputStream(dest));
}
}
Definition of part.write()
method is written in class org.apache.catalina.core.ApplicationPart
@Override
public void write(String fileName) throws IOException {
File file = new File(fileName);
// testing whether the path is absolute or not, OP's code is relative path
if (!file.isAbsolute()) {
// HIGHLIGHTED PART
file = new File(location, fileName);
}
try {
fileItem.write(file);
} catch (Exception e) {
throw new IOException(e);
}
}
In the write
method absolute path is being created by using location
variable. Variable location
hold the value of ROOT
directory of TOMCAT
as example
/tmp/tomcat.8080.12533880900101227658/work/Tomcat/localhost/ROOT/
So, when you do not give an absolute path to write
, function simply decide to move the file to ROOT
directory. In other word, file is being moved, working properly, OP just does not know where to look for the moved file.
What can be done to resolve OP''s issue.
class ControllerClass {
// Create an absolute base path where your uploaded file will be moved.
// All file will be moved here
private final String uploadFilePath = "/a/suitable/path/";
@PostMapping("/form3")
public String handleFormUpload3(@RequestParam("file") MultipartFile file) throws IOException {
String fileName = file.getOriginalFilename();
File file1 = new File(uploadFilePath, fileName);
//if(!file1.exists())
// file1.createNewFile();
file.transferTo(file1);
System.out.println(file1.exists());
return "redirect:uploadSuccess";
}
}
PS
This is poor judgement of coding by Spring Boot development team. They have overwridden function that has different behvior. This is bad principle for writing library. It is unwise to force programmer to be hyper aware of how functions with same name behave. It just create distrust towards the library. Both of the functions should have behave exactly the same. My apporach would be simpley call the other function with proper value instead of writing a whole new function with different nature.