Skip to content

Instantly share code, notes, and snippets.

@akobashikawa
Last active September 17, 2023 20:04
Show Gist options
  • Save akobashikawa/314e40aa53f71c955775ebb1e9c4c8d9 to your computer and use it in GitHub Desktop.
Save akobashikawa/314e40aa53f71c955775ebb1e9c4c8d9 to your computer and use it in GitHub Desktop.
Ejemplo de endpoint para mostrar imagen relativa al server en Spring Boot
/*
En application.properties:
server.error.whitelabel.enabled=false
spring.web.resources.static-locations=classpath:/static/
*/
package me.rulokoba.studio;
import java.net.MalformedURLException;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.UrlResource;
import org.springframework.http.MediaType;
import org.springframework.http.MediaTypeFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HolaController {
private final ResourceLoader resourceLoader;
public HolaController(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}
@GetMapping({"/holamundo/", "/hola/"})
public String holaMundo() {
return "Hola Mundo";
}
@GetMapping("/hola/{nombre}")
public String hola(@PathVariable("nombre") String nombre) {
return "Hola " + nombre;
}
@GetMapping("/images/{imageName}")
public ResponseEntity<Resource> getImage(@PathVariable String imageName) throws MalformedURLException {
// Usando un path absoluto
// Path imagePath = Paths.get("D:\\studio\\java\\springboot\\springboot-hola\\src\\main\\resources\\static\\img\\").resolve(imageName);
// System.out.println(imagePath);
// Resource resource = new UrlResource(imagePath.toUri());
// Usando un path relativo
System.out.println("classpath:/static/img/" + imageName);
Resource resource = resourceLoader.getResource("classpath:/static/img/" + imageName);
if (resource.exists() && resource.isReadable()) {
MediaType mediaType = MediaTypeFactory.getMediaType(resource).orElse(MediaType.APPLICATION_OCTET_STREAM);
return ResponseEntity.ok().contentType(mediaType).body(resource);
} else {
return ResponseEntity.notFound().build();
}
}
}
@JeanP2501
Copy link

Por alguna razón el problema seguía, cuando intentaba recuperar la imagen no actualizaba, siendo el mismo "src/main/resources/public/img" intente cambiarle de directorio y seguía el problema.
Se ha podido resolver con el siguiente código, además cambié la ruta donde guardo los archivos, lo colocaré todo en el controller para el ejemplo.

import org.springframework.core.io.Resource;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;

@GetMapping(value = "/images/{imageName:.+}")
public ResponseEntity<Resource> getImage(@PathVariable String imageName) {
	Path rutaFile = Paths.get("C:\\crm\\productos\\").resolve(imageName).toAbsolutePath();
	Resource resource = null;		
	try {
		resource = new UrlResource(rutaFile.toUri());
	} catch (MalformedURLException e) {
		e.printStackTrace();
	}
	
	if(!resource.exists() && !resource.isReadable()) {
		throw new RuntimeException("No se pudo cargar la imagen: " + imageName);
	}
	HttpHeaders cabecera = new HttpHeaders();
	cabecera.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"");
	
	return new ResponseEntity<Resource>(resource, cabecera, HttpStatus.OK);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment