最近接了一个新的功能,文件下载,由于之前一直是后端开发,和前端完全没有接触过,所以这个下载文件一个简单的操作也弄了好久,这不是有时间了,总结一下:
首先就这个文件格式来说有txt,html,doc,docx,xml等由于格式不一致,导致走了一些弯路,包括下载文件和网页预览
预览文件
//查看文件内容
function viewFile(aHtml) {
var filePath = $(aHtml).parent().parent().children('td').eq(4).children().html().replace("\\","/");
var fileFormat = $(aHtml).parent().parent().children('td').eq(5).children().html();
var fileName = $(aHtml).parent().parent().children('td').eq(0).children("span").eq(1).html();
if(fileFormat!="pdf" && fileFormat!="doc" && fileFormat!="docx" && fileFormat!="htm" && fileFormat!="html"){
layer.open({
type: 1,
offset: '50px',
skin: 'layui-layer-molv',
title: "查看内容",
area: ['800px', '500px'],
shade: 0,
shadeClose: false,
btn: ['返回'],
content: '<div><font style="margin-left:360px">文件内容</font></div><td style="width:800px"><div style="height: 380px;width:95%;float: left;margin-left: 20px"><textarea id="fileContentId" style="height: 380px;width:100%;overflow-y:auto"></textarea></div></td>',
});
$.ajax({
type: "POST",
url: baseURL + "cms/systemModuleFileCollect/viewFile",
dataType: "text",
data: {filePath: filePath,fileFormat: fileFormat},
success: function (data) {
//json对象转出对象
var dataVal = JSON.parse(data);
var fileContent = dataVal.fileContent;
$("#fileContentId").text(fileContent);
}
});
}else{
var url = baseURL+"modules/cms/previewFile.html";
var tempForm = document.createElement("form");
tempForm.method="post";
tempForm.action=url;
tempForm.target="_blank";
window.localStorage.setItem("source", "fileCollect");
window.localStorage.setItem("filePath",filePath);
window.localStorage.setItem("fileFormat", fileFormat);
window.localStorage.setItem("fileName", fileName);
document.body.appendChild(tempForm);
tempForm.submit();
document.body.removeChild(tempForm);
}
};
转入新的预览文件页面
<div style="width:100%;height:100%">
<iframe id="mainframe" style="width:100%;height:100%;"></iframe>
</div>
$(function () {
window.history.replaceState(null, null, window.location.href);
var mainIframe = document.getElementById('mainframe');
var fileName=window.localStorage.getItem("fileName");
var filePath=window.localStorage.getItem("filePath");
var fileFormat=window.localStorage.getItem("fileFormat");
if(fileName!=null && fileName.lastIndexOf(".")!=-1){
fileName=fileName.substring(0,fileName.lastIndexOf("."));
}
document.title=fileName;
if(fileFormat=="pdf"){
mainIframe.src="../../statics/plugins/pdf/web/viewer.html?file=http://"+window.location.host+"${request.contextPath}/cms/systemModuleFileCollect/previewPdf?filePath%3D"+encodeURIComponent(filePath);
}else if(fileFormat=="doc" || fileFormat=="docx" || fileFormat=="htm" || fileFormat=="html") {
mainIframe.src = baseURL + "cms/systemModuleFileCollect/previewWordOrHtml?filePath=" + filePath;
}
});
不同文件类型,访问不同的后端接口,其中pdf格式的文件借助pdf.js插件在前端展示,要注意pdf预览的路径问题,及跨域问题的解决
@RequestMapping(value = "/previewPdf", method = RequestMethod.GET)
public void previewPdf(String filePath, HttpServletResponse response) {
File file = new File(filePath);
if (file.exists()) {
byte[] data = null;
try {
FileInputStream input = new FileInputStream(file);
data = new byte[input.available()];
input.read(data);
response.getOutputStream().write(data);
input.close();
} catch (Exception e) {
logger.error("pdf预览错误");
}
} else {
logger.warn("文件不存在");
}
}
@RequestMapping(value = "/previewWordOrHtml", method = RequestMethod.GET)
public void previewWordOrHtml(String filePath,HttpServletResponse response) {
File file = new File(filePath);
String fileName=file.getName();
String fileFormat=fileName.substring(fileName.lastIndexOf("."),fileName.length());
ServletOutputStream out;
String aimPath="";
if (fileFormat.equals(".doc")) {
aimPath = filePath.replace(".doc",".html");
DocToHtml docToHtml = new DocToHtml();
try {
docToHtml.docToHtml(filePath,aimPath, EncodingDetect.getJavaEncode(filePath));
} catch (Exception e) {
e.printStackTrace();
logger.error("word文件预览错误");
}
} else if (fileFormat.equals(".docx")) {
aimPath = filePath.replace(".docx",".html");
DocxToHtml test = new DocxToHtml();
try {
test.docxToHtml(filePath,aimPath);
} catch (Exception e) {
logger.error("word文件预览错误");
return;
}
}else{
aimPath=filePath;
}
File htmlFile=new File(aimPath);
if(htmlFile.exists()){
try {
FileInputStream inputStream = new FileInputStream(htmlFile);
out = response.getOutputStream();
int b = 0;
byte[] buffer = new byte[1024];
while ((b = inputStream.read(buffer)) != -1) {
out.write(buffer, 0, b);
}
inputStream.close();
out.flush();
out.close();
} catch (Exception e) {
logger.error("文件预览错误");
}finally {
if(!(fileFormat.equals("html") && fileFormat.equals("htm"))){
htmlFile.delete();
}
}
}else {
logger.warn("文件不存在");
}
}
import org.apache.commons.io.FileUtils;
import org.apache.poi.hwpf.HWPFDocumentCore;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.converter.WordToHtmlUtils;
import org.apache.poi.hwpf.usermodel.Picture;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
import java.util.Base64;
/**
*
* doc转html处理
*/
public class DocToHtml{
public void docToHtml( String sourcePath,String aimPath,String encode) throws IOException, ParserConfigurationException, TransformerException {
HWPFDocumentCore wordDocument = WordToHtmlUtils.loadDoc(new FileInputStream(sourcePath));
WordToHtmlConverter wordToHtmlConverter = new ImageConverter(
DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument()
);
wordToHtmlConverter.processDocument(wordDocument);
Document htmlDocument = wordToHtmlConverter.getDocument();
ByteArrayOutputStream out = new ByteArrayOutputStream();
DOMSource domSource = new DOMSource(htmlDocument);
StreamResult streamResult = new StreamResult(out);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer serializer = transformerFactory.newTransformer();
serializer.setOutputProperty(OutputKeys.ENCODING, encode);
serializer.setOutputProperty(OutputKeys.INDENT, "yes");
serializer.setOutputProperty(OutputKeys.METHOD, "html");
serializer.transform(domSource, streamResult);
out.flush();
out.close();
String result = new String(out.toByteArray());
FileUtils.writeStringToFile(new File(aimPath), result, encode);
}
public class ImageConverter extends WordToHtmlConverter{
public ImageConverter(Document document) {
super(document);
}
@Override
protected void processImageWithoutPicturesManager(Element currentBlock, boolean inlined, Picture picture){
Element imgNode = currentBlock.getOwnerDocument().createElement("img");
StringBuffer sb = new StringBuffer();
sb.append(Base64.getMimeEncoder().encodeToString(picture.getRawContent()));
sb.insert(0, "data:" + picture.getMimeType() + ";base64,");
imgNode.setAttribute("src", sb.toString());
currentBlock.appendChild(imgNode);
}
}
}
import fr.opensagres.poi.xwpf.converter.xhtml.Base64EmbedImgManager;
import fr.opensagres.poi.xwpf.converter.xhtml.XHTMLConverter;
import fr.opensagres.poi.xwpf.converter.xhtml.XHTMLOptions;
import org.apache.commons.io.FileUtils;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import java.io.*;
/**
*
* docx转html处理
*/
public class DocxToHtml {
public void docxToHtml( String sourcePath,String aimPath) throws IOException {
FileInputStream fileInputStream=new FileInputStream(sourcePath);
XWPFDocument docxDocument = new XWPFDocument(fileInputStream);
XHTMLOptions options = XHTMLOptions.create();
//图片转base64
options.setImageManager(new Base64EmbedImgManager());
// 转换htm11
ByteArrayOutputStream htmlStream = new ByteArrayOutputStream();
XHTMLConverter.getInstance().convert(docxDocument, htmlStream, options);
fileInputStream.close();
docxDocument.close();
htmlStream.flush();
htmlStream.close();
String result = new String(htmlStream.toByteArray());
FileUtils.writeStringToFile(new File(aimPath), result, "utf-8");
}
}
用到的maven依赖:
<dependency>
<groupId>fr.opensagres.xdocreport</groupId>
<artifactId>xdocreport</artifactId>
<version>2.0.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>4.1.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>4.1.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>ooxml-schemas</artifactId>
<version>1.4</version>
</dependency>
好了,预览的话就到这里了,下篇文章在写关于下载的吧