在某些项目中,数据库的文档表中使用了二进制流字段(blob)来保存Office文档,PageOffice也是可以支持在线打开此类二进制流文件的。
首先,编写一个下载文件的后台方法,比如:openStream;
然后,把此openStream方法的url地址传递给PageOfficeCtrl对象的webOpen的第一个参数即可打开;
最后,保存文件时,调用FileSaver对象的getFileBytes()或getFileStream()获取到文件二进制流并保存到数据库中。
后端代码
- 编写下载文件的后台方法:openStream;
@RequestMapping(value = "openStream", method = RequestMethod.GET) public void openStream(HttpServletRequest request, HttpServletResponse response) throws SQLException, ClassNotFoundException, IOException { String id = request.getParameter("id"); Class.forName("org.sqlite.JDBC"); String strUrl = "jdbc:sqlite:" + ResourceUtils.getURL("classpath:").getPath() + "static/demodata/DataBase.db"; Connection conn = DriverManager.getConnection(strUrl); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("select * from stream where id = " + id); if (rs.next()) { //******读取数据库中文件流 开始******************************* byte[] imageBytes = rs.getBytes("Word"); int fileSize = imageBytes.length; response.reset(); // application/msword, application/x-excel, application/ms-powerpoint, application/pdf response.setContentType("application/msword"); response.setHeader("Content-Disposition", "attachment; filename=down.doc"); //fileN应该是编码后的(utf-8) response.setContentLength(fileSize); OutputStream outputStream = response.getOutputStream(); outputStream.write(imageBytes); outputStream.flush(); outputStream.close(); outputStream = null; //******读取数据库中文件流 结束******************************* } rs.close(); conn.close(); } - 在后端编写代码调用webOpen方法打开文件之前给SaveFilePage属性赋值(设置好保存时由哪个地址接口负责接收处理控件上传的文件流);
PageOfficeCtrl poCtrl = new PageOfficeCtrl(request); poCtrl.setSaveFilePage("saveStream?id=123"); // 设置保存文件的接口地址 //webOpen的第一个参数支持能够输出下载文件的Url相对地址或者文件在服务器上的磁盘路径两种方式 //查看详细,请在本站搜索“PageOffice属性或方法中涉及到的URL路径或磁盘路径的说明” poCtrl.webOpen("openStream?id=123", OpenModeType.docNormalEdit, "张佚名"); // 打开文件注意
对PageOfficeCtrl对象的所有属性赋值或函数调用都必须在WebOpen方法调用之前执行,否则会不生效。
3.在SaveFilePage属性指向的地址接口saveStream中,创建FileSaver对象处理文件的保存工 作。
@RequestMapping("saveStream")
public void saveStream(HttpServletRequest request, HttpServletResponse response)
throws ClassNotFoundException, FileNotFoundException, SQLException {
FileSaver fs = new FileSaver(request, response);
String id = request.getParameter("id").trim();
Class.forName("org.sqlite.JDBC");
String strUrl = "jdbc:sqlite:"
+ ResourceUtils.getURL("classpath:").getPath() + "static/demodata/DataBase.db";
Connection conn = DriverManager.getConnection(strUrl);
String sql = "UPDATE Stream SET Word=? where ID=" + id;
PreparedStatement pstmt = null;
pstmt = conn.prepareStatement(sql);
pstmt.setBytes(1, fs.getFileBytes());
//pstmt.setBinaryStream(1, fs.getFileStream(),fs.getFileSize());
pstmt.executeUpdate();
pstmt.close();
conn.close();
fs.close();
}