Create a Download according to element id

0

I created a system that uploads several files, however I ran into the following problem: I need to create a way to download according to the id of the element in the database. I wonder if anyone has an idea that I can take advantage of to do this function. I created a method in my controller, but it did not work as I wanted.

follows the method I created:

@RequestMapping(value = "/download/{file_name}", method = RequestMethod.GET)
public ModelAndView downloadFile(@PathVariable("fileName") String fileName, HttpServletResponse response){


    Path arquivo = Paths.get(fileName + ".pdf");

    if(Files.exists(arquivo)){

        response.setHeader(" Content-Disposition","attachment, filename=\"" + fileName + ".pdf" + "\"");
        response.setContentType(" application/pdf");
        try {

            Files.copy(arquivo, response.getOutputStream());
            response.getOutputStream().flush();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    return new ModelAndView(REQUEST_MAPPING_PAGE_PESQUISAR_ITO);
}
    
asked by anonymous 03.07.2017 / 14:48

2 answers

0

You can do this:

import org.springframework.core.io.InputStreamResource;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;

public class Teste {

    @RequestMapping(value = "download/{id:.+}", method = RequestMethod.GET, produces = "application/pdf")
    public ResponseEntity<InputStreamResource> downloadArquivo(@PathVariable(value = "id") String id) throws Exception {
        byte[] file = buscaArquivoPorId(id);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment", "document.pdf");
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentLength(file.length);

        return new ResponseEntity<>(new InputStreamResource(new ByteArrayInputStream(file)), headers, HttpStatus.OK);
    }

}
    
03.07.2017 / 16:39
0

Oops, here's my solution:

public static final Path uploadingdir = "caminho do arquivo";

@GetMapping("/{nome:.*}")
public void downloadPDFResource(HttpServletRequest request, HttpServletResponse response,
        @PathVariable("nome") String fileName) {

    Path file = Paths.get(uploadingdir.toString(), fileName);
    if (Files.exists(file)) {
        response.setContentType("application/pdf");
        response.addHeader("Content-Disposition", "attachment; filename=" + fileName);
        try {
            Files.copy(file, response.getOutputStream());
            response.getOutputStream().flush();
        } catch (IOException e) {
            throw new RuntimeException("Erro baixar arquivo", e);
        }
    }
}

Just look at the path of the file you are looking for.

    
07.07.2017 / 21:45