Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

uploaded image does not display until I refresh the page Spring Mvc

I'm using spring mvc with thymeleaf to upload an image to the server and display it after submitting the form in a separate page "result".

the problem is the image is not displayed until I refresh resources folder "resources/static/images" in Spring Tool Suite and then refresh the page. I modified eclipse workspace options to refresh automatically and the ide part solved but still need to refresh the result page to get the image displayed

This is the controller code

@RequestMapping(value = "/save", method = RequestMethod.POST)
public String contentSubmit(@Valid @ModelAttribute ContentEntity cm, BindingResult result,
        @RequestParam("file") MultipartFile file, Model model) {
    if (!file.isEmpty()) {
        try {
            cm.setImgUrl(file.getOriginalFilename());
            byte[] bytes = file.getBytes();
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File("src/main/resources/static/images/"+cm.getImgUrl())));
            stream.write(bytes);
            stream.close();
        } catch (Exception e) {
            //return error page
        }
    }

    if (result.hasErrors()) {
        return "cms";
    }

    contentDao.addContent(cm);
    return "view";
}

and this is the view code

<img th:src="@{'images/'+${contentEntity.imgUrl}}" class="image-responsive thumbnail" />
like image 519
Mohamed Zaki Avatar asked Aug 08 '15 11:08

Mohamed Zaki


1 Answers

You are pragmatically creating a resource (image file) in "src/resources/..." directory. However it appears that your server is serverig images fromm different directory( say target/** or bin/**). So when you refreshing the resource directory, STS does detect the new file is recently created and then it copy the file under target directory.

There is an option in eclipse "native hooks or polling" which constantly monitor the resources for changes (even though the are made externally to STS/eclipse) . As soon as it detect the changes, resources will get refreshed automatically.

You may want to set this option via: Preferences > General > Workspaces > "Refresh using native hooks or polling"

enter image description here

Hope this helps.

like image 153
skadya Avatar answered Oct 20 '22 19:10

skadya