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

4
  • The fact that you're using a relative path is probably part of the problem. Commented Jan 3, 2019 at 8:40
  • Probably the image isn't in the built jar file by maven. Commented Jan 3, 2019 at 8:42
  • @chrylis - updated question with absolute path. Tried this registry.addResourceHandler("uploads/**").addResourceLocations("/home/vkumar/apps/contest/uploads/") Commented Jan 3, 2019 at 8:46
  • @Wes - yes files are not in jar as those would be uploaded dynamically. Commented Jan 3, 2019 at 8:47

1 Answer 1

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); } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.