You can create this method inside your controller to find the images you upload in a folder called upload
at the same height as your directory src
.
@GetMapping("/uploads/{filename:.+}")
public ResponseEntity<Resource> verFoto(@PathVariable String filename) {
Path pathFoto = Paths.get("uploads").resolve(filename).toAbsolutePath();
log.info("pathFoto: "+ pathFoto);
Resource recurso = null;
try {
recurso = new UrlResource(pathFoto.toUri());
if (!recurso.exists()|| !recurso.isReadable()) {
throw new RuntimeException("No se puede cargar la imagen: " + pathFoto.getFileName());
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ResponseEntity
.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" +recurso.getFilename()+"\"")
.body(recurso);
}
To upload the files you can use this other method.
@PostMapping("/form")
public String guardar(@Valid Cliente cliente, BindingResult br, Map<String, Object> model,
@RequestParam("file") MultipartFile foto, RedirectAttributes flash, SessionStatus status) {
if (br.hasErrors()) {
model.put("titulo", "Formulario de cliente");
return "form";
}
if (!foto.isEmpty()) {
String uniqueFilename = UUID.randomUUID().toString() + "_" + foto.getOriginalFilename();
Path rootPath = Paths.get("upload").resolve(uniqueFilename);
Path rootAbsolutPath = rootPath.toAbsolutePath();
log.info("rootPath:" + rootPath);
log.info("rootAbsolutPath: " + rootAbsolutPath);
try {
Files.copy(foto.getInputStream(), rootAbsolutPath);
flash.addFlashAttribute("info", "Has subido correctamente " + uniqueFilename);
cliente.setFoto(uniqueFilename);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
String mensajeFlash = (cliente.getId() != null) ? "Cliente editado con éxito." : "Cliente creado con éxito.";
clienteService.save(cliente);
/**
* Cierra la sesión que se empezo con @SessionAttributes('Clientes')
*/
status.setComplete();
flash.addFlashAttribute("success", mensajeFlash);
return "redirect:/listar";
}
With thymeleaf you access the image with this tag:
<img th:src="@{'/upload/'} + ${cliente.foto}">
The arroba is very important. As an additional comment in this code I am defining the @sessionAttributes
to not directly use the id
with type="hidden"
. If this is not your case you have to remove status.setComplete();
and you also have to remove SessionStatus status
of the parameters of the method.