关于集成第三方office的sdk产品,采用servlet方式将数据库表BLOB字段文件下载与二进制文件上传到blob

本文详细介绍了一种使用JavaScript集成Office插件的方法,包括创建新文档及从服务器打开已有文档的功能实现。文中提供了具体的代码示例,展示了如何配置文档属性,并通过Servlet处理数据库BLOB字段的文件下载和上传。
摘要由CSDN通过智能技术生成

一般的office的厂家会提供多种产品的集成方式,这里介绍的是使用js集成office插件;作为一个入职3个月的小白,碰巧公司让我研究一下这个第三方产品,主要完成数据库表bolb文件下载与使用该office文件修改后的上传,本人在此把这些分享给大家,不足之处大家包涵!!!

1.这个便是厂家提供的js方法

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>DeepLink App</title>
    <script src="office.sdk.js"></script>
</head>
<body>
<h5>安卓/苹果 DeepLinks(URL Schemas) 适用</h5>
<button οnclick="createNewWordDocument()">新建word文档</button>
<button οnclick="openServerWordDocument()">打开服务器word文档</button>
<button οnclick="openServerPDFDocument()">打开服务器pdf文档</button>
<script type="text/javascript">
    
    // 启用DeepLinks
    Office.enabledDeepLinks();

    function createNewWordDocument() {

        var word = Office.newWordDocument();

        // COMPATIBLE 指的是doc/xls/ppt格式的文档
        // LATEST 指的是docx/xlsx/pptx的文档
        word.version = OfficeVersion.LATEST;
        word.fileName = "新建空白文档";
        word.uploadURL = "http://www.ntko.com:1986/mobileoffice/servlet/UploadServlet?filename=blank.docx&filetype=docx";

        var config = Office.newWordDocumentConfig();
        // 添加自定义表单参数

        var authHeader = new FormField();
        authHeader.name = "Authorization";
        authHeader.value = "Bearer eyJhbGciOiJSUzI1N....";

        var field2 = new FormField();
        field2.name = "key1";
        field2.value = "value1";

        config.formFields.push(authHeader);
        config.formFields.push(field2);

        // 配置文档属性
        config.enableHandWrite = true;
        config.enableRevision = true;
        config.enableCopy = true;
        config.enableEditComment = true;
        config.enablePrint = true;
        config.enableSaveAs = true;
        config.enableSendMail = true;
        config.enableShare = true;
        config.enableExportToPDF = true;

        // 设置文档属性
        word.config = config;

        // 新建空白文档
        Office.createNewWord(word);
    }

    function openServerWordDocument() {
        var word = Office.newWordDocument();
        word.fileName = "201703131703.doc";
        word.downloadURL = "http://www.ntko.com:1986/mobileoffice/servlet/DownloadServlet?filename=201703131703.doc";
        word.uploadURL = "http://www.ntko.com:1986/mobileoffice/servlet/UploadServlet?filename=201703131703.doc&filetype=doc";

        var config = Office.newWordDocumentConfig();

        // 添加自定义表单参数
        var field1 = new FormField();
        field1.name = "key1";
        field1.value = "value1";
        var field2 = new FormField();
        field2.name = "key1";
        field2.value = "value1";

        config.formFields.push(field1);
        config.formFields.push(field2);

        var bookmarkRep1 = new FormField();
        bookmarkRep1.name = "ReplaceHere";
        bookmarkRep1.value = "这是第一个书签替换后的值";

        var bookmarkRep2 = new FormField();
        bookmarkRep2.name = "ReplaceHere";
        bookmarkRep2.value = "这是第二个书签替换后的值";

        config.bookmarkReplacement.push(bookmarkRep1);
        config.bookmarkReplacement.push(bookmarkRep2);

        // 配置文档属性
        config.enableHandWrite = true;
        config.enableRevision = true;
        config.enableCopy = true;
        config.enableEditComment = true;
        config.enablePrint = true;
        config.enableSaveAs = true;
        config.enableSendMail = true;
        config.enableShare = true;
        config.enableExportToPDF = true;

        // 设置文档属性
        word.config = config;

        // 打开服务器文档
        Office.openWordFromURL(word);
    }

    function openServerPDFDocument() {
        var pdf = Office.newPDFDocument();
        pdf.fileName = "NTKOPDF.pdf";
        pdf.downloadURL = "http://www.ntko.com:1986/mobileoffice/servlet/DownloadServlet?filename=NTKOPDF.pdf";
        pdf.uploadURL = "http://www.ntko.com:1986/mobileoffice/servlet/UploadServlet?filename=NTKOPDF.pdf&filetype=pdf";

        var config = Office.newPDFDocumentConfig();

        // 用户名称
        config.username = "Hybrid 测试用户";
        // 打开手写笔功能
        config.usePenMode = true;

        // 添加自定义表单参数
        var field1 = new FormField();
        field1.name = "key1";
        field1.value = "value1";
        var field2 = new FormField();
        field2.name = "key1";
        field2.value = "value1";

        config.formFields.push(field1);
        config.formFields.push(field2);

        // 配置文档属性
        config.enableEdit = true;
        config.enableCopy = true;
        config.enablePrint = true;
        config.enableSaveAs = true;
        config.enableShareAndSendMail = true;

        // 设置文档属性
        pdf.config = config;

        // 打开服务器文档
        Office.openPDFFromURL(pdf);
    }
</script>
</body>
</html>
其实主要就是2个方法,一个就是关于创建新的文档,一个是打开一个已经存在文档;

 主要就是这两个属性:word.downloadURL与word.uploadURL 
word.downloadURL是一个下载文件的url;word.downloadURL则是负责文件上传url;实现这两个url的上传下载;
2.由于对.net项目不了解(本人刚学习java啊...),所以只好采用servlet的方式将数据库BLOB的文件进行下载,将二进制格式的文件传入数据库blob格式的字段(通过world.download下载的文件,厂家会提供一个字段来获取二进制文件,此处字段为“fileUpload”)

package Servlet;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Properties;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * Servlet implementation class UpServlet
 */
public class FileServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public FileServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		String filename = request.getParameter("filename");// 下载的文件名
		String flag = request.getParameter("flag");// 区分上传下载参数
		String tName = request.getParameter("tName");// 操作的表名
		String DM_CODE = request.getParameter("DM_CODE");// 表的主键
		String clumName = request.getParameter("clumName");// blob数据的列名
		if (flag.equalsIgnoreCase("UP")) {
			upfile(request, response, tName, DM_CODE, clumName, filename);
		}
		if (flag.equalsIgnoreCase("DOWN")) {
			downfile(request, response, tName, DM_CODE, clumName, filename);
		}
		if (flag.equalsIgnoreCase("UPDATE")) {
			updateFile(request, response, tName, DM_CODE, clumName);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

	public void updateFile(HttpServletRequest request, HttpServletResponse response, String tName, String DM_CODE,
			String clumName) throws ServletException, IOException {
		InputStream in = null;
		Connection conn = null;
		InputStream indata = null;
		PreparedStatement pst = null;
		try {
			// 解析http请求
			boolean isMultipart = ServletFileUpload.isMultipartContent(request);
			// 解析成功
			if (isMultipart == true) {
				// 获得磁盘文件条目工厂
				FileItemFactory factory = new DiskFileItemFactory();
				// 高水平的API文件上传处理,将文件保存在服务器硬盘
				ServletFileUpload upload = new ServletFileUpload(factory);
				// 设置上传的单个文件的大小100M
				upload.setSizeMax(100 * 1024 * 1024);
				// 设置上传的总文件的大小100M
				upload.setFileSizeMax(100 * 1024 * 1024);
				List<FileItem> fileItemList = upload.parseRequest(request);
				// 如果表单内容不为空
				if (fileItemList != null) {
					// 遍历请求内容
					for (FileItem fileItem : fileItemList) {
						if (fileItem.getFieldName().equalsIgnoreCase("fileUpload")) {
							in = fileItem.getInputStream();
							byte[] buffer = new byte[in.available()];
							indata = getServletContext().getResourceAsStream("/WEB-INF/datebase.properties");
							Properties props = new Properties();
							try {
								props.load(indata);
							} catch (IOException e) {
								e.printStackTrace();
								return;
							}
							String driver = props.getProperty("db.driver");
							String URL = props.getProperty("db.url");
							String USER = props.getProperty("db.username");
							String PASSWORD = props.getProperty("db.password");
							// 1.加载驱动程序
							Class.forName(driver);
							// 2.获得数据库链接
							conn = DriverManager.getConnection(URL, USER, PASSWORD);
							// 3.通过数据库的连接操作数据库,实现增删改查(使用Statement类)
							String s = "update " + tName + " set " + clumName + "=? where DM_CODE=" + DM_CODE;
							pst = conn.prepareStatement(s);
							pst.setBinaryStream(1, in, buffer.length);
							pst.execute();
							fileItem.delete();
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if(indata!=null){
				indata.close();}
				if(pst!=null){
				pst.close();}
				if(conn!=null){
				conn.close();}
				if(in!=null){
				in.close();}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	protected void downfile(HttpServletRequest request, HttpServletResponse response, String tName, String DM_CODE,
			String clumName, String filename) throws ServletException, IOException {
		InputStream indata = null;
		Connection conn = null;
		PreparedStatement pst = null;
		ServletOutputStream out = null;
		InputStream ins = null;
		try {
			out = response.getOutputStream();
			response.reset();
			
			response.setContentType("application/msword;charset=GBK");
			indata = getServletContext().getResourceAsStream("/WEB-INF/datebase.properties");
			Properties props = new Properties();
			try {
				props.load(indata);
			} catch (IOException e) {
				e.printStackTrace();
				return;
			}
			String driver = props.getProperty("db.driver");
			String URL = props.getProperty("db.url");
			String USER = props.getProperty("db.username");
			String PASSWORD = props.getProperty("db.password");
			// 1.加载驱动程序
			Class.forName(driver);
			// 2.获得数据库链接
			conn = DriverManager.getConnection(URL, USER, PASSWORD);
			// 3.通过数据库的连接操作数据库,实现增删改查(使用Statement类)
			if (tName.equals("RD_FILE")) {
				String sql = "select " + clumName + ",FILENAME from " + tName + " where DM_CODE=" + DM_CODE + "";
				pst = conn.prepareStatement(sql);
				ResultSet rs = pst.executeQuery();
				if (rs.next()) {
					java.sql.Blob blob = rs.getBlob(clumName);
					ins = blob.getBinaryStream();
					String fname=rs.getString("FILENAME");
					response.setHeader("Content-Disposition", "attachement;filename=" + fname + ";");
					// 下面将BLOB数据写入文件
					byte[] b = new byte[1024];
					int len = 0;
					while ((len = ins.read(b)) != -1) {
						out.write(b, 0, len);
					}
				}
			} else {
				String sql = "select " + clumName + " from " + tName + " where DM_CODE=" + DM_CODE + "";
				pst = conn.prepareStatement(sql);
				ResultSet rs = pst.executeQuery();
				if (rs.next()) {
					java.sql.Blob blob = rs.getBlob(clumName);
					ins = blob.getBinaryStream();
					response.setHeader("Content-Disposition", "attachement;filename=" + filename + ";");
					// 下面将BLOB数据写入文件
					byte[] b = new byte[1024];
					int len = 0;
					while ((len = ins.read(b)) != -1) {
						out.write(b, 0, len);
					}
				}
			}
		} catch (Exception e) {

			e.printStackTrace();

		} finally {
			indata.close();
			ins.close();
			out.flush();
			out.close();
			try {
				pst.close();
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public void upfile(HttpServletRequest request, HttpServletResponse response, String tName, String DM_CODE,
			String clumName, String filename) throws ServletException, IOException {
		InputStream in = null;
		Connection conn = null;
		InputStream indata = null;
		PreparedStatement pst = null;
		try {
			// 解析http请求
			boolean isMultipart = ServletFileUpload.isMultipartContent(request);
			// 解析成功
			if (isMultipart == true) {
				// 获得磁盘文件条目工厂
				FileItemFactory factory = new DiskFileItemFactory();
				// 高水平的API文件上传处理,将文件保存在服务器硬盘
				ServletFileUpload upload = new ServletFileUpload(factory);
				// 设置上传的单个文件的大小100M
				upload.setSizeMax(100 * 1024 * 1024);
				// 设置上传的总文件的大小100M
				upload.setFileSizeMax(100 * 1024 * 1024);				
				List<FileItem> fileItemList = upload.parseRequest(request);				
				if (fileItemList != null) {
					// 遍历请求内容
					for (FileItem fileItem : fileItemList) {
						if (fileItem.getFieldName().equalsIgnoreCase("fileUpload")) {
							in = fileItem.getInputStream();
							byte[] buffer = new byte[in.available()];
							indata = getServletContext().getResourceAsStream("/WEB-INF/datebase.properties");
							Properties props = new Properties();
							try {
								props.load(indata);
							} catch (IOException e) {
								e.printStackTrace();
								return;
							}
							String driver = props.getProperty("db.driver");
							String URL = props.getProperty("db.url");
							String USER = props.getProperty("db.username");
							String PASSWORD = props.getProperty("db.password");
							// 1.加载驱动程序
							Class.forName(driver);
							// 2.获得数据库链接
							conn = DriverManager.getConnection(URL, USER, PASSWORD);
							// 3.通过数据库的连接操作数据库,实现增删改查(使用Statement类)
							// 如果操作的表为RD_FILE,则需修改sql
							String s;
							if (tName.equals("RD_FILE")) {
								String filetype = filename.split("\\.")[1];
								s = "insert into " + tName + "(DM_CODE," + clumName + ",RD_TYPE,FILENAME) values('"
										+ DM_CODE + "',?,'" + filetype + "','" + filename + "')";
							} else {
								s = "insert into " + tName + "(DM_CODE," + clumName + ") values(" + DM_CODE + ",?)";
							}
							pst = conn.prepareStatement(s);
							pst.setBinaryStream(1, in, buffer.length);
							pst.execute();
							fileItem.delete();
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				indata.close();
				pst.close();
				conn.close();
				in.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
3.配置servlet把2个访问地址传入相应url即可;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值