Create Public Folder SpringMVC

-1

In the current project I have a webservice (API-REST) this has a control panel where they fill out the forms to identify via web this webservice

the detail is in that I do not know how to create a public folder example currently in the form that I have already requested the image and I keep it in the folder

main / resource / static / ImagenesDelTalServicio /

now practically in a database I relate the route with the service so I could know exactly the path of the file and be able to extract it but I do not know how to extract or download any idea

    
asked by Monster 09.06.2018 в 06:29
source

1 answer

0

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.

    
answered by 11.06.2018 в 19:27