Home > Net >  Save uploaded picture to static/pictures in spring boot [duplicate]
Save uploaded picture to static/pictures in spring boot [duplicate]

Time:10-02

Edit: After further investigation it seems pretty obvious that I can't write to /static. I need to write the files elsewhere and direct the Thymeleaf to read from that location.

I am trying to upload a picture to my spring boot application, placing it in static/pictures so that the thymeleaf html page can read the picture. But I am unable to find out how to specify the path to that folder.

There is no problem saving the file to System.getProperty("user.dir");

//working
private String userDirectory = System.getProperty("user.dir");
//Not working
private String userDirectory = "/static/pictures";
@PostMapping("/upload")
public String singleFileUpload(@RequestParam("file") MultipartFile file,
                               RedirectAttributes redirectAttributes) {

I would like the upload path to point to /static/pictures but will always get java.nio.file.NoSuchFileException no matter how I define the path.

        // Get the file and save it somewhere
        byte[] bytes = file.getBytes();
        Path path = Paths.get( uploadPath   file.getOriginalFilename());
        Files.write(path, bytes);

        redirectAttributes.addFlashAttribute("message",
                "You successfully uploaded '"   file.getOriginalFilename()   "'");

    } catch (IOException e) {
        e.printStackTrace();
    }

    //return "redirect:/uploadStatus";
    return "index";
}

I have also tried setting upload.path in the properties file.

upload.path=/META-INF/resources/static/pictures/

CodePudding user response:

At a minimum, you will need to add an extra path separator,

i.e.

private String userDirectory = "/static/pictures/";

or

Path path = Paths.get(uploadPath   "/"   file.getOriginalFilename());
Files.write(path, bytes);

Since in your question as written you would end up with something like

"/static/picturesfilename"

rather than

"/static/pictures/filename"

Be aware also that what you are doing is extremely risky. The submitting user can, under certain circumstances, set getOriginalFilename(), and therefore write to

/static/pictures/../../etc/arbitrary

See https://github.com/spring-projects/spring-framework/issues/18237

CodePudding user response:

I use a static helper to do this like with org.springframework.util.ResourceUtils class

public static File getResourceAsFile(String relativeFilePath) throws FileNotFoundException {
    return ResourceUtils.getFile(String.format("classpath:%s",relativeFilePath));

}

And use like

File dir=getResourceAsFile("/static/pictures/");
  • Related