简体   繁体   中英

How to configure the path to the folder in the resources

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?

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, eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM