javaspring-booteclipse-jee

How can I change saving file directory?


I want to change saving file directory. Here is it my code:

@RequestMapping(value = "/UploadFile")
public String uploadFile(HttpServletResponse response String base64, String name, String size) throws Exception {
    byte[] decodedFile = Base64.getDecoder().decode(base64.getBytes(StandardCharsets.UTF_8));
    response.setContentType("application/octet-stream");
    response.setHeader("Content-Disposition", "attachment; filename=" + name);
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Cache-Control", "no-cache");

    InputStream is = new ByteArrayInputStream(decodedFile);
    IOUtils.copy(is, response.getOutputStream());
    response.flushBuffer();
    return "true";
}

Solution

  • Try this:

     File path = new File("YOUR PATH HERE") ;
                try (FileOutputStream fos = new FileOutputStream(path)) {
                    fos.write(decodedFile);
                } catch (IOException e) {
                    e.printStackTrace();
                }
    

    You should also consider reading these links:

    https://medium.com/javarevisited/how-to-upload-files-to-local-directory-in-spring-boot-c8c33f8239d3

    https://spring.io/guides/gs/uploading-files/

    EDIT

    If String name is original File name, you could also do this:

    File path = new File("C:\\YOUR_PATH\\images\\" + name);