要找台电脑安装officeServier,这里我就不说了,我只说在安装成功后如何在网页展示文件
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nriet.business.bean.FileInfo;
@RestController
@RequestMapping(value = "/officeOnline")
public class OfficeOnlineController {
private static Logger log = Logger.getLogger(OfficeOnlineController.class);
// office服务地址
@Value("${office.http.server.host}")
private String officeServer;
//项目地址
@Value("${office.http.wopi.host}")
private String officeUrl;
private static final String CHARSET_UTF8 = "UTF-8";
/**
* office跳转
*
* @param path
* @param response
* @param request
* @throws IOException
*/
@RequestMapping(value = "/officeView")
@ResponseBody
public void officeView(HttpServletResponse response,String path) throws IOException {
String urlTmp =officeServer+ officeUrl;
String aspx = "";
if (path.endsWith(".pptx") || path.endsWith(".PPTX") || path.endsWith(".ppt") || path.endsWith(".PPT")) {
aspx = "p/PowerPointFrame.aspx";
} else if (path.endsWith(".doc") || path.endsWith(".docx") || path.endsWith(".DOCX") || path.endsWith(".DOC")) {
aspx = "wv/wordviewerframe.aspx";
} else if (path.endsWith(".xlsx") || path.endsWith(".XLSX") || path.endsWith(".xls") || path.endsWith(".XLS")) {
aspx = "x/_layouts/xlviewerinternal.aspx";
}
path = path.replaceAll("/", "_q_");
path = path.replaceAll("\\.", "_d_");
urlTmp = urlTmp.replace("{aspx}", aspx);
path = URLEncoder.encode(path,CHARSET_UTF8);
path = URLEncoder.encode(path,CHARSET_UTF8);
urlTmp = urlTmp.replace("{path}", path);
log.info(urlTmp);
response.sendRedirect(urlTmp);
}
@RequestMapping(value = "/wopi/files/{path}", method = RequestMethod.GET)
public void getFileWopiInfo(@PathVariable("path") String path, HttpServletResponse response) {
FileInfo info = new FileInfo();
try {
//逗号转义
path = path.replace("_d_", ".");
//目录转义
path = path.replace("_q_", "/");
//文件路径
String filePath = URLDecoder.decode(path, "UTF-8");
String officePath = "";;
if(officePath == null)
officePath = "";
String fileName = officePath + filePath;
log.info(fileName);
if (fileName != null && fileName.length() > 0) {
File file = new File(fileName);
if (file.exists()) {
info.setBaseFileName(file.getName());
info.setSize(file.length());
info.setOwnerId("admin");
info.setVersion(file.lastModified());
info.setSha256(getHash256(file));
}
}
ObjectMapper mapper = new ObjectMapper();
response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
response.getWriter().write(mapper.writeValueAsString(info));
} catch (Exception e) {
e.printStackTrace();
}
}
@RequestMapping(value = "/wopi/files/{path}/contents", method = RequestMethod.GET)
public void downFile(@PathVariable("path") String path, HttpServletResponse response) {
//逗号转义
path = path.replace("_d_", ".");
//目录转义
path = path.replace("_q_", "/");
String officePath ="";
if(officePath == null)
officePath = "";
String fileName = officePath + path;
File file = new File(fileName);
String filename = file.getName();
try (InputStream fis = new BufferedInputStream(new FileInputStream(fileName));
OutputStream toClient = new BufferedOutputStream(response.getOutputStream())) {
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
// 清空response
response.reset();
// 设置response的Header
response.addHeader("Content-Disposition", "attachment;filename=" +
new String(filename.getBytes(CHARSET_UTF8), "ISO-8859-1"));
response.addHeader("Content-Length", String.valueOf(file.length()));
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
toClient.write(buffer);
toClient.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 获取文件的SHA-256值
* @param file
* @return
*/
private String getHash256(File file) throws IOException, NoSuchAlgorithmException {
String value = "";
try (InputStream fis = new FileInputStream(file)) {
byte[] buffer = new byte[1024];
int numRead;
// 返回实现指定摘要算法的 MessageDigest 对象
MessageDigest digest = MessageDigest.getInstance("SHA-256");
do {
numRead = fis.read(buffer);
if (numRead > 0) {
// 更新摘要
digest.update(buffer, 0, numRead);
}
} while (numRead != -1);
value = new String(Base64.encodeBase64(digest.digest()));
}
return value;
}
}
这个是office.properties文件的信息,服务器地址就是我们安装了微软服务的那台电脑的ip(这里ip是瞎写的哦,我是不会写真实地址的,不信你们可以自己试试看);本机地址就是我自己电脑的ip加Tomcat的端口号(当然也是假的啦,请按自己需求修改),本机地址也可以理解为项目所在的ip地址
#服务器地址
office.http.server.host=http://177.19.20.13/{aspx}?WOPISrc=
#本地地址
office.http.wopi.host=http://192.166.45.11:8080/yn/officeOnline/wopi/files/{path}
这个是文件实体
import com.fasterxml.jackson.annotation.JsonProperty;
import java.io.Serializable;
/**
* 文件属性对象
*
* 由于wopi的接口不遵守驼峰命名规则,所以需要用@JsonProperty指定别名
*/
public class FileInfo implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* 文件名
*/
@JsonProperty("BaseFileName")
private String baseFileName;
/**
* 文件所有者的唯一编号
*/
@JsonProperty("OwnerId")
private String ownerId;
/**
* 文件大小,以bytes为单位
*/
@JsonProperty("Size")
private long size;
/**
* 文件的256位bit的SHA-2编码散列内容
*/
@JsonProperty("SHA256")
private String sha256;
/**
* 文件版本号,文件如果被编辑,版本号也要跟着改变
*/
@JsonProperty("Version")
private long version;
/**
* 允许外部服务的连接
*/
@JsonProperty("AllowExternalMarketplace")
private boolean allowExternalMarketplace = true;
/**
* 更改文件的权限
*/
@JsonProperty("UserCanWrite")
private boolean userCanWrite = true;
/**
* 是否支持更新
*/
@JsonProperty("SupportsUpdate")
private boolean supportsUpdate = true;
/**
* 是否支持锁定
*/
@JsonProperty("SupportsLocks")
private boolean supportsLocks = true;
public String getBaseFileName() {
return baseFileName;
}
public void setBaseFileName(String baseFileName) {
this.baseFileName = baseFileName;
}
public String getOwnerId() {
return ownerId;
}
public void setOwnerId(String ownerId) {
this.ownerId = ownerId;
}
public long getSize() {
return size;
}
public void setSize(long size) {
this.size = size;
}
public String getSha256() {
return sha256;
}
public void setSha256(String sha256) {
this.sha256 = sha256;
}
public long getVersion() {
return version;
}
public void setVersion(long version) {
this.version = version;
}
public boolean isAllowExternalMarketplace() {
return allowExternalMarketplace;
}
public void setAllowExternalMarketplace(boolean allowExternalMarketplace) {
this.allowExternalMarketplace = allowExternalMarketplace;
}
public boolean isUserCanWrite() {
return userCanWrite;
}
public void setUserCanWrite(boolean userCanWrite) {
this.userCanWrite = userCanWrite;
}
public boolean isSupportsUpdate() {
return supportsUpdate;
}
public void setSupportsUpdate(boolean supportsUpdate) {
this.supportsUpdate = supportsUpdate;
}
public boolean isSupportsLocks() {
return supportsLocks;
}
public void setSupportsLocks(boolean supportsLocks) {
this.supportsLocks = supportsLocks;
}
@Override
public String toString() {
return "FileInfo{" +
"baseFileName='" + baseFileName + '\'' +
", ownerId='" + ownerId + '\'' +
", size=" + size +
", sha256='" + sha256 + '\'' +
", version=" + version +
", allowExternalMarketplace=" + allowExternalMarketplace +
", userCanWrite=" + userCanWrite +
", supportsUpdate=" + supportsUpdate +
", supportsLocks=" + supportsLocks +
'}';
}
}
最后是请求。这个都不陌生吧?Tomcat地址,端口号,项目名,请求路径,“C:/Desktop/测试/测试.docx”这个就是文件所在路径了,因为我是本地文件,其他环境我没试过,路径中必须是“/”。简单说下,将文件路径传给后台,后台进行解析传给我们的officeServer,officeServer解析完毕后,再传回来,我们就能在网页展示了。当然也有其他问题这个展示顶部会有office的图标
<iframe src='http://localhost:8082/yyyyy/officeOnline/officeView.do?path=C:/Desktop/测试/测试.docx'></iframe>