二进制流保存到文件/二进制流浏览器输入文件

二进制流保存到文件/二进制流浏览器输入文件

/**********此段代码是把二进制流byte[]生成文件 START******************/ epolicyPdfSavePath=getEpolicyPdfSavePath(); if (epolicyPdfSavePath != null && !epolicyPdfSavePath.endsWith(File.separator)) { epolicyPdfSavePath = epolicyPdfSavePath + File.separator; } //文件子路径 String filePath = ePolicyBean.getId(); //以文件名保存 String path = epolicyPdfSavePath + File.separator + filePath; File actSavedFilePath = new File(path); // 如果路径不存在,则创建文件夹 if (!actSavedFilePath.exists()) { try { FileUtils.forceMkdir(actSavedFilePath); } catch (IOException e) { e.printStackTrace(); } } String fileName = ePolicyBean.getId() +"."+ "pdf"; String fullPath = actSavedFilePath + File.separator + fileName; //文件流 byte[] pdfFile = ePolicyBean.getPdfFile(); log.debug("pdf生成返回完整路径为:"+fullPath); log.debug("epolicyCCAU"+epolicyCCAU); getFileFromBytes(pdfFile, fullPath); /**********此段代码是把二进制流byte[]生成文件 END******************/ // 下面是输出(一定要注意编码) // 取得 HttpServletResponse /**********以文件输出流的形式把文件给输出到浏览器 START******************/ HttpServletResponse response = ServletActionContext.getResponse(); ByteArrayInputStream in = null; try { response.setContentType("application/pdf"); //此处注释 表明是可以直接用浏览器打开。加上则表示打开一个下载文件的窗口 // response.setHeader("Content-Disposition", "attachment; filename=" + fileName); //文件输入流 OutputStream os = response.getOutputStream(); in =new ByteArrayInputStream(pdfFile); int tp = 0; byte[] tmpByte=new byte[4096]; while (true) { tp = in.read(tmpByte); if(tp <= 0){ break; } response.getOutputStream().write(tmpByte, 0, tp); } os.flush(); } catch (Throwable e) { throw new RuntimeException("文件下载失败!", e); } finally { try { in.close(); } catch (IOException e) { throw new RuntimeException("关闭流失败!", e); } }















/** * 把文件流保存成物理文件 * @param b * @param outputFile * @return */ public static File getFileFromBytes(byte[] b, String outputFile) { BufferedOutputStream stream = null; File file = null; try { file = new File(outputFile); FileOutputStream fstream = new FileOutputStream(file); stream = new BufferedOutputStream(fstream); stream.write(b); } catch (Exception e) { e.printStackTrace(); } finally { if (stream != null) { try { stream.close(); } catch (IOException e1) { e1.printStackTrace(); } } } return file; }





你可能感兴趣的:(String,Stream,浏览器,File,null,byte)