gpt4 book ai didi

java - 从 Outputstream 下载 PDF 文件

转载 作者:行者123 更新时间:2023-11-30 12:07:56 28 4
gpt4 key购买 nike

我正在使用这个方法来获取一个文件

@GetMapping(value = "/test", produces = MediaType.APPLICATION_PDF_VALUE)
public String test() throws FOPException, IOException {

SisDocuments document = documentRepository.getOne(Long.valueOf("801859"));

documentService.constructDocumentById(document);


return "/connexion";
}

@Override
public void constructDocumentById(SisDocuments document) {

try {

File inputFile = new File("input.txt");

File xsltfile = new File(path + "dz/sis-fop.xsl");
FopFactory fopFactory = FopFactory.newInstance();
FOUserAgent foUserAgent = fopFactory.newFOUserAgent();

ByteArrayOutputStream bout = new ByteArrayOutputStream();


OutputStream out;
out = new java.io.FileOutputStream("employee.pdf");

try {
Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out);

TransformerFactory factory = TransformerFactory.newInstance();
Source xslt = new StreamSource(xsltfile);
Transformer transformer = factory.newTransformer(xslt);

File fXmlFile = new File(path + "dz/my-file.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);

Result res = new SAXResult(fop.getDefaultHandler());

DOMSource source = new DOMSource(doc);

transformer.transform(source, res);



} finally {
}

} catch (Exception e) {
System.err.println(" r " + e.getMessage());
e.printStackTrace();
}

}

此方法是在我的项目目录中创建一个文件,我想下载它而不是创建它

最佳答案

典型的方法是将文件作为 InputStream 并将其写入 ResponseOutputStream

@GetMapping(value = "/test/{idDocument}", produces = MediaType.APPLICATION_PDF_VALUE)
public void test(@PathVariable("idDocument") String idDocument, HttpServletRequest request,
HttpServletResponse response) throws FOPException, IOException {

SisDocuments document = documentRepository.getOne(Long.valueOf(idDocument));

documentService.constructDocumentById(document);

try {
// // get your file as InputStream
File f = new File("employee.pdf");
InputStream is = new FileInputStream(f);

org.apache.commons.io.IOUtils.copy(is, response.getOutputStream());

// copy it to response's OutputStream
response.addHeader("Content-disposition", "attachment; filename=" + "employee.pdf");
response.setContentType("application/pdf");
response.flushBuffer();
} catch (IOException ex) {
throw new RuntimeException("IOError writing file to output stream");
}

}

关于java - 从 Outputstream 下载 PDF 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54575788/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com