0
votes

I wanted to upload dynamic images and serve them using <img> tag, so I followed this solution: Spring Boot images uploading and serving

Absolute path of project: /home/vkumar/apps/contest

Absolute path of upload dir: /home/vkumar/apps/contest/uploads

ResourceConfig.java

public class ResourceConfig implements WebMvcConfigurer {

@Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/uploads/**").addResourceLocations("file:uploads/");
  }
}

Then I uploaded a file in uploads dir test.jpg

Now If I go to the server and run the app using the command

mvn spring-boot:run

and open image http://example.com:8080/uploads/test.jpg

all work fine, I can see an image which been uploaded however If I create jar using the command

mvn clean package

I see the error "This application has no explicit mapping for /error, so you are seeing this as a fallback."

1
The fact that you're using a relative path is probably part of the problem. - chrylis -cautiouslyoptimistic-
Probably the image isn't in the built jar file by maven. - Wes
@chrylis - updated question with absolute path. Tried this registry.addResourceHandler("uploads/**").addResourceLocations("/home/vkumar/apps/contest/uploads/") - VK321
@Wes - yes files are not in jar as those would be uploaded dynamically. - VK321

1 Answers

0
votes

You can create a controller method to load the uploaded files.

You can follow this guide: https://spring.io/guides/gs/uploading-files/

or this concise example on pastebin. https://pastebin.com/yDr61Emm

Sample code below:

@GetMapping("/pictures/{filename:.+}")
    @ResponseBody
    public ResponseEntity<Resource> serveFile(@PathVariable String filename) {

        Path path = rootLocation.resolve(filename);
        Resource file = null;
        try {
            file = new UrlResource(path.toUri());
        } catch (MalformedURLException ex) {
            Logger.getLogger(UploadController.class.getName()).log(Level.SEVERE, null, ex);
        }
        return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION,
                "attachment; filename=\"" + file.getFilename() + "\"").body(file);
    }