一、引言
本篇文章講的是SpringBoot和永中DCS整合,實現word、pdf、excel、ppt等文檔的在線預覽。
在網上看了很多資料:
第一個看到的是微軟的“office online server”,這個太複雜了,需要安裝中間件,安裝還對系統有要求,必須是“windows server 2012 r2”或“Windows Server 2016”,但是這款是不收費的。
第二個看到的是永中的DCS,提供了兩種使用方式,一種是jar包調用,主要適合java語言調用;一種是http請求方式調用,支持各種開發語言以標準Web服務方式提供調用,如搭配負載均衡服務器,可部署到多臺服務器上併發使用,實現集羣部署。
第三個看到的是點聚的WebOffice,這個也是免費的,但是嘛,下下來的demo…我就看看,不想說話。
最後我選擇使用永中DCS。
二、介紹
163、QQ等郵箱的附件預覽部分就是採用永中DCS服務實現的
永中 http://www.yozodcs.com/index.html (有免費版),永中DCS採用自主可控核心技術,具備快速技術和服務響應能力,把文檔原樣輸出爲HTML,圖片等,即點即得、無需下載、保護文檔隱私,快速高效,輕鬆實現文檔在線安全閱讀。
1.優缺點分析
(1)優點:無需下載、原樣展現文檔;支持各類PC端、移動端查看,減少流量消耗;開發部署簡單高效;最重要的是文件安全加密。
(2)缺點:缺點肯定是有的,只是剛開始使用,暫時還沒有缺點上的體驗。
2.先體驗一下
地址:http://www.yozodcs.com/page/example.html
說明:
1.使用該方法,文檔應該會被上傳到永中的服務器,非公開文檔不宜使用(購買的話應該也可以部署的自己的服務器上,不深究)。
2.下面測試方法中上傳的文檔不知道會不會被定時清理而不可用,不過如果有這個問題,只要申請免費受限賬號應該就可以了。
三、項目集成
1.實例環境準備
技術 | 版本 |
---|---|
JDK | 1.8 |
SpringBoot | 2.1.5 |
DCS | 3.4 |
Tomcat | 8.0.32 |
2.項目結構
3.項目配置
(1)pom.xml配置
<!-- 添加依賴(必須) -->
<!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.8</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpcore -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.11</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpmime -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.8</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.55</version>
</dependency>
<!-- 頁面配置 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
(2)application.properties配置
# 文件上傳下載和預覽,採用永中雲轉換進行文件預覽
office-online-yz.name=officeOnlineYZ
office-online-yz.version=v1.0
office-online-yz.officeOnlineDomain=http\://dcsapi.com/
office-online-yz.officeOnlineParmKey=?k\=
office-online-yz.officeOnlineKey=45728504936923136184773
office-online-yz.officeOnlineParmURL=&url\=http\://
office-online-yz.officeOnlineUrl=www.javakly.com
office-online-yz.profile=D\:/Java/javaWork/officeOnlineYZ/src/main/resources/upload
office-online-yz.downUrl=/files/dowload
4.工具類DCSUtil.java
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.ParseException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
/**
* @Description: DCS文檔轉換服務Java調用代碼示例
*/
public class DCSUtil {
/**
* 向指定 URL 發送POST方法的請求
* @param url 發送請求的 URL
* @param param 請求參數,請求參數應該是 name1=value1&name2=value2 的形式。
* @return 所代表遠程資源的響應結果
*/
public static String sendPost(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打開和URL之間的連接
URLConnection conn = realUrl.openConnection();
conn.setRequestProperty("Accept-Charset", "UTF-8");
// 設置通用的請求屬性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 發送POST請求必須設置如下兩行
conn.setDoOutput(true);
conn.setDoInput(true);
// 獲取URLConnection對象對應的輸出流
out = new PrintWriter(conn.getOutputStream());
// 發送請求參數
out.print(param);
// flush輸出流的緩衝
out.flush();
// 定義BufferedReader輸入流來讀取URL的響應
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("發送 POST 請求出現異常!" + e);
e.printStackTrace();
}
// 使用finally塊來關閉輸出流、輸入流
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
/**
* 向指定 URL 上傳文件POST方法的請求
*
* @param url 發送請求的 URL
* @param filepath 文件路徑
* @param type 轉換類型
* @return 所代表遠程資源的響應結果, json數據
*/
public static String SubmitPost(String url, String filepath, String type) {
String requestJson = "";
HttpClient httpclient = new DefaultHttpClient();
try {
HttpPost httppost = new HttpPost(url);
FileBody file = new FileBody(new File(filepath));
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null,
Charset.forName("UTF-8"));
reqEntity.addPart("file", file); // file爲請求後臺的File upload;屬性
reqEntity.addPart("convertType", new StringBody(type, Charset.forName("UTF-8")));
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
HttpEntity resEntity = response.getEntity();
requestJson = EntityUtils.toString(resEntity);
EntityUtils.consume(resEntity);
}
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
// requestJson = e.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
// requestJson = e.toString();
} finally {
try {
httpclient.getConnectionManager().shutdown();
} catch (Exception ignore) {
}
}
return requestJson;
}
}
5.WEB調用
(1)上傳文檔
引入ajaxfileupload.js(jQuery-File-Upload)
<input id="fileupload" type="file" name="file"><!-- name值需爲file,與永中接口參數名對應 -->
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script src="js/jquery.ui.widget.js"></script>
<script src="js/jquery.fileupload.js"></script>
<script>
$(function() {
$('#fileupload').fileupload({
url: 'http://dcs.yozosoft.com:80/upload',
dataType: 'json',
formData: {
convertType: "0"
},
done: function(e, data) {
console.log(data.result);
}
});
});
</script>
(2)URL文檔
$.ajax({
url: "http://dcs.yozosoft.com:80/onlinefile", //服務地址
data: {
downloadUrl: "http://www.snpdp.com/file-download-1064.html", //要預覽的文檔地址
convertType: "0"
},
dataType: "json",
type: "post",
success: function(data) {
console.log(data);
//window.location=data.data[0];
},
error: function(data) {
console.error(data)
}
});
接口說明、convertType參數取值說明、返回參數說明:http://www.yozodcs.com/help.html#link14
6.測試
@Test
public void testDCS() {
// 文件上傳轉換
String convertByFile = DCSUtil.SubmitPost("http://dcs.yozosoft.com:80/upload", "D:/test/doctest.doc", "0");
System.out.println(convertByFile);
// 輸出:{"result":0,"data":["http://dcs.yozosoft.com:8000/2019/04/12/MTkwNDEyNTM5NTE2Njk5.html"],"message":"轉換成功","type":0}
// 網絡地址轉換
String convertByUrl = DCSUtil.sendPost("http://dcs.yozosoft.com:80/onlinefile",
"downloadUrl=http://www.snpdp.com/file-download-1064.html&convertType=1");
System.out.println(convertByUrl);
// 輸出:{"result":0,"data":["http://dcs.yozosoft.com:8000/2019/04/12/MTkwNDEyNTQ0NjcyMDI3.html"],"message":"轉換成功","type":1}
}
四、結束語
以上就是具體的SpringBoot框架下結合永中DCS實現文檔的在線預覽,我們可以通過登錄DCS官網,註冊獲取自己的賬號,然後對需要進行預覽的文檔直接遠程調用接口實現文檔在線預覽(具體操作,參考網站的幫助文檔有詳細解釋)。