最近项目中遇到一个需求,需要在手机端实现对pc端上传的附件进行在线预览,整理了一下实现方案,仅供参考
首先是最常见的我word在线预览,这里使用的是com.aspose.words这个jar包(其他格式的也可以用这种方式,需要引用对应格式的jar包,没有找到免费的,所以换了别的方式实现)
实现方式
1.引入jar包
<dependency>
<groupId>com.aspose</groupId>
<artifactId>words</artifactId>
<version>14.9.0</version>
<classifier>jdk16</classifier>
</dependency>
2.后台实现
//获取文件实体
FileVO fileVO = this.facade.getFileService().loadObject(objectId, FileVO.class);
//判断是否为word文档
if (fileVO.getFileName().indexOf(".doc") > -1 || fileVO.getFileName().indexOf(".docx") > -1) {
//自定义文件夹
String floder = LawConfig.officeHtml + subFolder(objectId);
//自定义html文件路径
String htmlPath = floder + objectId + "_" + fileVO.getVersion() + ".html";
//判断是否已经生成过html文件
if (new File(htmlPath).exists()) {
System.out.println("文件已存在");
} else {
System.out.println("新文件");
//本项目附件有单独的服务器,这里获取的是附件服务器的连接
URL url = new URL(Global.imgServer + "?file=" + fileVO.getFilePath() + "&name="
+ URLEncoder.encode(fileVO.getFileName(), "utf-8"));
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
if (!new File(floder).exists()) {
new File(floder).mkdirs();
}
DataInputStream input = new DataInputStream(conn.getInputStream());
String filename = fileVO.getFileName();
Boolean flag = request.getHeader("User-Agent").indexOf("like Gecko") > 0;
if (request.getHeader("User-Agent").toLowerCase().indexOf("msie") > 0 || flag) {
filename = URLEncoder.encode(filename, "UTF-8");// IE浏览器
} else {
// 先去掉文件名称中的空格,然后转换编码格式为utf-8,保证不出现乱码,
// 这个文件名称用于浏览器的下载框中自动显示的文件名
filename = new String(filename.replaceAll(" ", "").getBytes("UTF-8"), "ISO8859-1");
}
filename=filename.replaceAll("\\+","%20");
response.setContentType(fileVO.getFileType());
//response.addHeader("Content-Disposition", "attachment;fileName=" + filename);// 设置文件名
byte[] buffer = new byte[1024];
BufferedInputStream bis = null;
//由于文件可能是加密的,这里选择先下载文件到服务器然后判断是否需要解密
File file=new File(LawConfig.officeHtml+fileVO.getFileName());
FileOutputStream out=new FileOutputStream(file,true);
try {
bis = new BufferedInputStream(input);
//OutputStream os = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
out.write(buffer, 0, i);
i = bis.read(buffer);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
out.close();
}
//本项目中上传的附件可能会加密,这里判断是否需要解密
System.setProperty("user.dir", "加密接口对应路径");
InteKey mInteKey = new InteKey();
System.out.println("开始验证,文件是:"+LawConfig.officeHtml + fileVO.getFileName());
int ia = mInteKey.Ia(LawConfig.officeHtml + fileVO.getFileName());
System.out.println("验证结果:" + ia);
if (ia == 0) {
// 加密文件,需要做解密处理
System.out.println("开始解密");
int da = mInteKey.Da(LawConfig.officeHtml + fileVO.getFileName(), LawConfig.officeHtml + fileVO.getFileName());
System.out.println("解密结果:" + da);
}
//这一步是关键,指定保存成HTML类型文件,这里的文件路径可以是真实路径,也可以是流
new Document(LawConfig.officeHtml + fileVO.getFileName()).save(htmlPath, SaveFormat.HTML);
}
//将生成的html文件以流的形式写回浏览器
FileInputStream fis = null;
OutputStream os = null;
fis = new FileInputStream(htmlPath);
os = response.getOutputStream();
int count = 0;
byte[] buffer = new byte[1024 * 8];
while ((count = fis.read(buffer)) != -1) {
os.write(buffer, 0, count);
os.flush();
}
fis.close();
os.close();
3.前台引用
function readOnline(){
$('.details_centent').on('click','.download',function(){
var objectId=$(this).attr('data-objectId');
var fName = $(this).text();
var fileSuffix = fName.substr(fName.lastIndexOf('.'));
function isInformatData(arr, val ) {
val = val.toLowerCase();
return arr.indexOf(val)!=-1;
};
if(isInformatData(['.doc', '.docx','.xls','.xlsx'], fileSuffix)){
//doc,docx
var url='/law/common/file/downloadOrDetail.htm?objectId='+objectId;
window.open(url);
}else if(isInformatData(['.pdf'], fileSuffix)){
//pdf
window.open ("/page/common/mobilePhone/contract/pdf.jsp?fileId="+objectId);
}else if(isInformatData(['.txt'], fileSuffix)){
//txt
window.open ("/page/common/mobilePhone/model/txt.jsp?objectId="+objectId);
}else if(isInformatData(['.jpg','.png','.bmp','.jpeg','.gif'], fileSuffix)){
//图片
window.open ("/page/common/mobilePhone/model/img.jsp?objectId="+objectId);
}else{
//其他
alert("该类型不支持预览,请于电脑端查看!");
}
})
}