Home > Mobile >  Upload image in resource folder Spring boot
Upload image in resource folder Spring boot

Time:04-11

I tried to upload image as static folder in resource folder. But what is problem with this is I can't access images by URL. Can you offer solution for this ?

CodePudding user response:

It is pretty easy to create a microservice to upload and access images.

The following code is an example I wrote for some exercise in which you create a subfolder for each user, to avoid names' conflict.

Tell me if it is clear enough, or I can explain.

@RestController
@RequestMapping("")
public class Images {

    private void saveFile(String uploadDir, String filename, MultipartFile multipartFile) throws IOException {
        Path uploadPath = Paths.get(uploadDir);

        if (!Files.exists(uploadPath)) {
            Files.createDirectories(uploadPath);
        }

        try (InputStream inputStream = multipartFile.getInputStream()) {
            Path filePath = uploadPath.resolve(filename);
            Files.copy(inputStream, filePath, StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException ioe) {
            throw new IOException("Could not save image file: "   filename, ioe);
        }
    }

    @PostMapping("/upload")
    public void upload(@RequestParam String userID, @RequestParam("image") MultipartFile multipartFile) {

        String fileName = StringUtils.cleanPath(Objects.requireNonNull(multipartFile.getOriginalFilename()));
        String uploadDir = "user-photos/"   userID;

        try {
            saveFile(uploadDir, fileName, multipartFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "get/{userID}/{imageName}", method = RequestMethod.GET)
    public ResponseEntity<Resource> getImage(@PathVariable String userID, @PathVariable String imageName) {

        File file = new File(String.format("user-photos/%s/%s", userID, imageName));

        HttpHeaders header = new HttpHeaders();
        header.add("Cache-Control", "no-cache, no-store, must-revalidate");
        header.add("Pragma", "no-cache");
        header.add("Expires", "0");

        Path path = Paths.get(file.getAbsolutePath());
        ByteArrayResource resource;
        try {
            resource = new ByteArrayResource(Files.readAllBytes(path));
        } catch (IOException e) {
            e.printStackTrace();
            throw new ResponseStatusException(HttpStatus.NOT_FOUND);
        }

        return ResponseEntity.ok()
                .headers(header)
                .contentLength(file.length())
                .contentType(MediaType.IMAGE_JPEG)
                .body(resource);
    }
}

CodePudding user response:

I also faced same problem while fetching the images and find this solution.

In spring application you don't need URl. It renders the images from the resource/static/images folder as default path. If there is no images folder then create one and put all your images in resource/static/images folder and just use source default path to access the images.

e.g.:-

   <div >
    <div style=" background-color: blue;">
        <div id="carouselExampleIndicators"  data-ride="carousel" style="width: 1000px; float: right;">
            <ol >
                <li data-target="#carouselExampleIndicators" data-slide-to="0" ></li>
                <li data-target="#carouselExampleIndicators" data-slide-to="1"></li>
                <li data-target="#carouselExampleIndicators" data-slide-to="2"></li>
                <li data-target="#carouselExampleIndicators" data-slide-to="3"></li>
            </ol>
            <div >
                <div >
                    <img  src="images/zoom3.png" alt="First slide">
                </div>
                <div >
                    <img  src="images/zoom2.png" alt="Second slide">
                </div>
                <div >
                    <img  src="images/zoom1.jpg" alt="Third slide">
                </div>
                <div >
                    <img  src="images/zoom4.png" alt="Fourth slide">
                </div>
            </div>
            <a  href="#carouselExampleIndicators" role="button" data-slide="prev">
                <span  aria-hidden="true"></span>
                <span >Previous</span>
            </a>
            <a  href="#carouselExampleIndicators" role="button" data-slide="next">
                <span  aria-hidden="true"></span>
                <span >Next</span>
            </a>
        </div>
    </div>
</div>

project structure

enter image description here

CodePudding user response:

Finally I could able to fix this problem, we need not specify the file: prefix, and moreover by default resourceLoader.getResource() will look for resources in the root directory of our web application, So no need of specifying the webapp folder name. So finally the following code works for me

  • Related