0

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."

VK321
  • 5,768
  • 3
  • 44
  • 47

1 Answers1

0

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);
    }
Olantobi
  • 869
  • 1
  • 8
  • 16