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 ?
>Solution :
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);
}
}