This answer is not a standard way to get application root path (file system path). I need to upload a file to a directory e.g. uploads created in application main directory. How can I get the application root path in my Java Class. I am developing Rest API. Please help in this regard.
Spring Boot, by default, serves content on the root context path (“/”).
properties in default location. Spring Boot loads the application. properties file automatically from the project classpath. All you have to do is to create a new file under the src/main/resources directory.
The entry point of the Spring Boot Application is the class contains @SpringBootApplication annotation. This class should have the main method to run the Spring Boot application. @SpringBootApplication annotation includes Auto- Configuration, Component Scan, and Spring Boot Configuration.
If I understand right, you want to develop a REST API which aims to upload a file to directory that located in your application directory. It's recommended to create file,images,.. in resources directory. And basically you should be using servlet context to get the absolute path of this directory. First you need servletContext
@Autowired
ServletContext context;
Then you can get absolute and relative directory("resources/uploads"):
String absolutePath = context.getRealPath("resources/uploads");
File uploadedFile = new File(absolutePath, "your_file_name");
EDITED:
You would like to develop rest api. So you can create a controller class first
@RestController
@RequestMapping("/file")
public class FileController {
@Autowired
ServletContext context;
@PostMapping("/upload")
public String fileUpload(@RequestParam("file") MultipartFile file) {
if (file.isEmpty()) {
throw new RuntimeException("Please load a file");
}
try {
// Get the file and save it uploads dir
byte[] bytes = file.getBytes();
Path path = Paths.get(context.getRealPath("uploads") + file.getOriginalFilename());
Files.write(path, bytes);
} catch (IOException e) {
e.printStackTrace();
}
return "success";
}
}
There is another way to manage file operations and Spring Boot documentation explained very well: Uploading Files Spring Boot
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With