Home > Enterprise >  How to configure the path to the folder in the resources
How to configure the path to the folder in the resources

Time:01-25

I want to receive files and save them in a folder inside resources. I have this endpoint

public ResponseEntity<String> uploadPhoto(@RequestParam("file") MultipartFile file) {
        try {

            String photoName = file.getOriginalFilename();
            String path = servletContext.getClassLoader().getResource("resources/static/photos/").getPath()   photoName;

            try (FileOutputStream fileOutputStream = new FileOutputStream(path)) {
                fileOutputStream.write(file.getBytes());
            }
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            log.info(e);
            return ResponseEntity.status(400).body(Exceptions.BAD_REQUEST.getMessage());
        }
    }

And locally it saves the file really to where I need it. But I also have a version of this application on the server. There I run a JAR with this application. My Dockerfile

FROM openjdk:11
ARG JAR_FILE=build/libs/appname-0.0.1-SNAPSHOT.jar
COPY ${JAR_FILE} /app.jar
ENTRYPOINT ["java","-jar","/app.jar"]

I tried to run the application in this form on the server, but there I get an error "There are no such directory". I tried

servletContext.getClassLoader().getResource() 

method and receive this path

file:/app.jar!/BOOT-INF/classes!/

What should I do to receive path to resources?

CodePudding user response:

I want to receive files and save them in a folder inside resources.

This is impossible. The 'resources' folder is in a nebulous, unknown location. Usually it's a bunch of entries in a jar file. The classpath abstraction does not support 'writing' into the classpath, and even if you attempt to use hackery to do it, the classpath is generally not writable; an app that can write to its own folders is a minor security faux pas, and on some OSes (notably windows), it's not so easy to replace an open file.

The right place to write files is generally the home dir, e.g. Paths.get(System.getProperty("user.home"), "myProjectName"). That, or, a place that the user can explicitly configure in a preferences dialog or a settings file.

  • Related