FileOutputStream 到 StreamedContent
FileOutputStream to StreamedContent
我正在使用 Apache POI 制作一个 Excel 文件,并将其保存到 FileOutputStream
。
在 XHTML 中,我想用 <p:fileDownload>
下载这个文件,但它需要 StreamedContent
才能工作。
我想知道如何将我的 FileOutputStream
解析或转换为 StreamedContent
以使用 PrimeFaces 下载它。
我不得不将我的文件保存到磁盘中,稍后使用文件类型再次读取它以将其保存到 StreamedContent 中。
代码:
HSSFWorkbook libro = new HSSFWorkbook();
FileOutputStream elFichero = new FileOutputStream("c:/Temp/MyExcel.xls");
libro.write(elFichero);
elFichero.close();
libro.close();
File fil = new File("c:/Temp/MyExcel.xls");
StreamedContent excel = new DefaultStreamedContent(new FileInputStream(fil), new MimetypesFileTypeMap().getContentType(fil), "MyExcel.xls"));
稍后我可以通过 <p:commandButton>
获取我的 excel 文件。
无论如何,我一直在寻找一种在下载前尽量不将其保存到磁盘的方法...
这是不将文件保存到磁盘的解决方案:
HSSFWorkbook workbook = new HSSFWorkbook();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
workbook.write(outputStream);
InputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
StreamedContent streamedContent = new DefaultStreamedContent(inputStream, "application/xls", "output.xls");
我正在使用 Apache POI 制作一个 Excel 文件,并将其保存到 FileOutputStream
。
在 XHTML 中,我想用 <p:fileDownload>
下载这个文件,但它需要 StreamedContent
才能工作。
我想知道如何将我的 FileOutputStream
解析或转换为 StreamedContent
以使用 PrimeFaces 下载它。
我不得不将我的文件保存到磁盘中,稍后使用文件类型再次读取它以将其保存到 StreamedContent 中。
代码:
HSSFWorkbook libro = new HSSFWorkbook();
FileOutputStream elFichero = new FileOutputStream("c:/Temp/MyExcel.xls");
libro.write(elFichero);
elFichero.close();
libro.close();
File fil = new File("c:/Temp/MyExcel.xls");
StreamedContent excel = new DefaultStreamedContent(new FileInputStream(fil), new MimetypesFileTypeMap().getContentType(fil), "MyExcel.xls"));
稍后我可以通过 <p:commandButton>
获取我的 excel 文件。
无论如何,我一直在寻找一种在下载前尽量不将其保存到磁盘的方法...
这是不将文件保存到磁盘的解决方案:
HSSFWorkbook workbook = new HSSFWorkbook();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
workbook.write(outputStream);
InputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
StreamedContent streamedContent = new DefaultStreamedContent(inputStream, "application/xls", "output.xls");