Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upload image to folder in spring mvc

I try to upload image to folder in my resource "/resouces/images/demo.jpg" but it could not run. Can you help to upload to my resource in spring mvc. If I upload to "C://test//demo.jpg", It's ok. My sample:

    String filename = File.separator + "resources"
                       + File.separator + "images" + File.separator
                       + filea.getOriginalFilename();
    outputStream = new FileOutputStream(filename);
    int readBytes = 0;
    byte[] buffer = new byte[8192];
    while ((readBytes = inputStream.read(buffer, 0, 8192)) != -1) {
        System.out.println("===ddd=======");
        outputStream.write(buffer, 0, readBytes);
    }
like image 640
Thanh Duy Ngo Avatar asked Dec 21 '13 14:12

Thanh Duy Ngo


1 Answers

Inject ServletContext like any other bean

@Autowired
ServletContext servletContext

then use

    String webappRoot = servletContext.getRealPath("/");
    String relativeFolder = File.separator + "resources" + File.separator
                             + "images" + File.separator
    String filename = webappRoot + relativeFolder
                       + filea.getOriginalFilename();
like image 107
Abhijit Mazumder Avatar answered Nov 03 '22 06:11

Abhijit Mazumder