Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Application Root Path of Spring Boot application

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.

like image 509
Bahadar Ali Avatar asked May 08 '17 11:05

Bahadar Ali


People also ask

What is the root directory of spring boot project?

Spring Boot, by default, serves content on the root context path (“/”).

How do you specify file path in application properties in spring boot?

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.

Where does spring boot application start?

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.


1 Answers

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

like image 143
fiskra Avatar answered Sep 21 '22 12:09

fiskra