这是我的文件路径

public final static String BOOKINGPDFFILE= "D:/Hotels/pdf/";


下面的代码是我从上面的资源文件夹下载pdf的内容

Pdf="column name in database  i used for storing in database"

@RequestMapping(value = "/getpdf/{pdf}", method = RequestMethod.GET)
public  void getPdf(@PathVariable("pdf") String fileName, HttpServletResponse response,HttpServletRequest request) throws IOException {


   try {
        File file = new File(FileConstant.BOOKINGPDFFILE + fileName+ ".pdf");


        Files.copy(file.toPath(),response.getOutputStream());
    } catch (IOException ex) {
        System.out.println("Contract Not Found");
        System.out.println(ex.getMessage());
    }

}

最佳答案

您可以尝试如下操作:

@RequestMapping(method = { RequestMethod.GET }, value = { "/downloadPdf")
    public ResponseEntity<InputStreamResource> downloadPdf()
    {
        try
        {
            File file = new File(BOOKINGPDFFILE);
            HttpHeaders respHeaders = new HttpHeaders();
            MediaType mediaType = MediaType.parseMediaType("application/pdf");
            respHeaders.setContentType(mediaType);
            respHeaders.setContentLength(file.length());
            respHeaders.setContentDispositionFormData("attachment", file.getName());
            InputStreamResource isr = new InputStreamResource(new FileInputStream(file));
            return new ResponseEntity<InputStreamResource>(isr, respHeaders, HttpStatus.OK);
        }
        catch (Exception e)
        {
            String message = "Errore nel download del file "+idForm+".csv; "+e.getMessage();
            logger.error(message, e);
            return new ResponseEntity<InputStreamResource>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }


在您的网页中,您可以通过以下方式编写链接:

<a href="/yourWebAppCtx/yourControllerRoot/downloadPdf" target="_blank"> download PDF </a>


安杰洛

10-07 18:56
查看更多