Upload photos to OpenShift. Spring MVC

2019-06-05 02:58发布

问题:

I have deployed .war file of my Spring MVC app at OpenShift server. There every user can change there photos. It works at my localhost, but i need to upload photo at OpenShift server and to put a path of every photo to database. This is my method for uploading files

@RequestMapping(value = "/user/updateinfo", method = RequestMethod.POST)
public String postAvatar(@RequestParam("file") MultipartFile file, Principal principal) {
    if (file.isEmpty()) {
        return "redirect:/user";
    }

    if (!file.isEmpty()) {
        try {
            String relativeWebPath = "/resources/avatars/";
            String absoluteFilePath = context.getRealPath(relativeWebPath);
            String name = file.getOriginalFilename();
            // String name=file.getOriginalFilename();
            System.out.println(absoluteFilePath);
            String path = absoluteFilePath + "/" + name;
            File convFile = new File(absoluteFilePath + "/" + name);
            this.usersService.addUserAvatar(principal.getName(), "/var/lib/openshift/56ae274f0c1e664bf3000158/app-root/data/"+name);
            System.out.println(convFile.getAbsolutePath());
            file.transferTo(convFile);
            System.out.println("You have uploaded file");
            return "redirect:/user";
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Failed to upload");
            return "redirect:/user";
        }
    }
    return " redirect:/user";
}

But this path doesn't work. Log file shows me this exception

    /var/lib/openshift/56ae274f0c1e664bf3000158/jbossews/null/vr833vqI_wc.jpg
java.io.FileNotFoundException: null/vr833vqI_wc.jpg (No such file or directory)

Help pls!

回答1:

Solved this problem adding <Context docBase="/var/lib/openshift/PROJECT_ID/app-root/data" path="/data" /> to the .openshift/config/server.xml into <HOST> tag. After that i could get my photos throught https://appname-domain.rhcloud.com/data/photo.jpg