Create a Download according to element id

Asked

Viewed 117 times

0

I created a system that uploads several files, but I ran into the following problem: I need to create a way to download according to the element id in the database. I wonder if anyone has an idea I can use to do that job. 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);
}

2 answers

0

You can do it like 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);
    }

}
  • is it mandatory that the return is in byte? , because I have only the file path in the database the image is in a directory inside my web server

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 have to watch the file path you are searching for.

  • you would call this method with a href himself or by the ajax ?

  • For a href. You need in an ajax?

  • 1

    is not a need more I believe that by Ajax I have more control to treat

  • Actually, it works with ajax yes. I tested it here.

  • So why do I believe my problem is at the time of the call.

  • Why it even reaches the method, more does not download the file.

  • Oops, you’ve solved your problem?

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.