Download and display images with timilif and springboot

This is my image boot code in Spring Boot:

String root = ctx.getRealPath("/");
File dir = new File(root + File.separatorChar + "images");
if (!dir.exists())
    dir.mkdir();

String path = dir.getAbsolutePath() + File.separatorChar
            + product.getProductName() + "."
            + file.getContentType().split("/")[1];
System.out.println(path);
File file1 = new File(path);
try {
    FileOutputStream fod = new FileOutputStream(file1);
    fod.write(file.getBytes());
    fod.close();
    product.setProductPicture("/images/" + product.getProductName()
            + "." + file.getContentType().split("/")[1]);
} catch (IOException e) {
    e.printStackTrace();
}

File uploading works fine, the only problem with this code is that when I use it ctx.getRealPath("/"), it returns a temporary location, and when I reload the spring boot application, I lose existing files that have already been downloaded since it creates a new temporary directory.

This causes some problems, since I also have to display these pictures on my site, and now it returns “image error not found”.

Therefore, I needed a solution that would allow me to upload files in a permanent place and serve them from there in a browser.

Note. I use the timeline for viewing.

+4
3

. , bytes[] :

@RequestMapping(value = "image/{imageName}")
@ResponseBody
public byte[] getImage(@PathVariable(value = "imageName") String imageName) throws IOException {

    File serverFile = new File("/home/user/uploads/" + imageName + ".jpg");

    return Files.readAllBytes(serverFile.toPath());
}

html <img alt="Image" th:src="@{image/userprofile}" width="250" height="250"/>

+5

.

1: .

enter image description here

2: ResourceConfig

    @Configuration
    public class ResourceConfig implements WebMvcConfigurer {

        @Override
        public void addResourceHandlers(final ResourceHandlerRegistry registry) {
            registry.addResourceHandler("/uploads/**").addResourceLocations("file:uploads/");
        }
    }

3: html thymleaf

<img th:src="@{'/uploads/' + ${someobject.someAttribute}}"/>
+1

Many thanks. I have to do this, but with the image repository in my db, as follows:

      @GetMapping("/muestra/{idproducto}")
  @ResponseBody
  public byte[] muestraImagen(Model model,
        //id of the product i need to show the picture
      @PathVariable("idproducto")Integer idproducto, HttpServletResponse response) {
        //object from database
    Productos producto = productosRepository.findByIdproducto(idproducto);
    logger.info("sal imagen yo te invoco");
    //return the attr of my object (blob)
    return producto.getArchivo();
  }

and in html:

<img alt="Image" th:src="@{/tienda/productos/muestra/{id}(id=${producto.idproducto})}" width="250" height="250"/>
Run code
-1
source

Source: https://habr.com/ru/post/1663438/


All Articles