怎么把php文件下载下来
headers.add("Content-Disposition", "attachment; filename=" + file.getName() );
return new ResponseEntity(IOUtils.toByteArray(in
headers.add("Content-Type", "application/pdf"); headers.add("Content-Disposition", "attachment; filename=" + file.getName() ); return new ResponseEntity(IOUtils.toByteArray(in), headers, HttpStatus.OK); } 该方法在浏览器中直接访问localhost:8080/pdfDownload就回弹出一个文件保存框,选择保存的本地路径即可下载,或者有的效果是直接在浏览器中下载了PDF文件,这是因为所使用的浏览器本身的下载设置,可以根据个人喜好来设置究竟弹出还是不弹出保存框。 二、浏览器预览PDF文件,再下载 如果使用的不是RestController,就可以直接返回一个String字符串,内容为PDF文件的视图名称,这里定义为helloWorldPDF,该视图名在views.properties中配置 @RequestMapping(value = "/pdfDownload2", method = GET) public String download2(HttpServletRequest request) throws IOException { return "helloWorldPDF"; } resource资源文件夹中的views.properties文件的内容为: helloWorldPDF.(class)=com.test.report.PDFView 这里的com.test.report.PDFView指的是定义的PDF视图的内容。 我们使用了itextpdf的jar包来生成PDF文件的内容。 compile group: 'com.itextpdf', name: 'itextpdf', version: '5.5.6' public class PDFView extends AbstractView { public PDFView() { setContentType("application/pdf"); } @Override protected boolean generatesDownloadContent() { return true; } @Override protected final void renderMergedOutputModel(Map model, HttpServletRequest request, HttpServletResponse response) throws Exception { ByteArrayOutputStream baos = createTemporaryOutputStream(); Document document = new Document(PageSize.A4); PdfWriter writer = PdfWriter.getInstance(document, baos); writer.setViewerPreferences(PdfWriter.ALLOW_PRINTING | PdfWriter.PageLayoutSinglePage); document.open(); Paragraph header = new Paragraph(new Chunk("hello world")); document.add(header); document.close(); writeToResponse(response, baos); } } 以上就生成了我们需要的PDF文件的内容php文件,并放进ByteArrayOutputStream中,调用writeToResponse方法把字节流传进response中。 因为使用的是SpringBootApplication,所以需要加的一些配置是在 Application 的包含main方法的class中进行的 @Bean public ResourceBundleViewResolver viewResolver() { ResourceBundleViewResolver resolver = new ResourceBundleViewResolver(); resolver.setOrder(1); resolver.setBasename("views"); return resolver; } 如此一来就可以直接在浏览器中访问localhost:8080/pdfDownload2看到PDF文件的预览页面,在页面中可以进行下载,打印等操作。 (编辑:成都站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |