需求介绍
前端通过ajax调用java的接口获取到json字符串,在通过js处理获取到的json字符串将文件内容展示在页面上,同时可以对文件下载。
Java后端代码
/**
* 获取文件内容
* @return
*/
public String getFileContent() {
Map<String, Object> fileMap = new HashMap<>();
fileMap.put("fileName", zsFiles.get(0).getAttachFileName());
//获取文件流
InputStream is = fileAttachService.getAttachStorageDetail(zsFiles.get(0).getAttachGuid()).getContent();
if (is == null) {
fileMap.put("fileContent", "");
return JsonUtil.controlsToJson(fileMap);
}
//获取文件流
byte[] fileBuff = null;
try {
fileBuff = this.inputStreamToByteArray(is);
if (is != null) {
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
fileMap.put("fileContent", Base64.encodeBase64String(fileBuff));
return JsonUtil.controlsToJson(fileMap);
}
/**
* 输入流转字节数组
* @param input
* @return
* @throws IOException
*/
private byte[] inputStreamToByteArray(InputStream input) throws IOException {
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int n = 0;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
}
return output.toByteArray();
}
前端html代码
<div>
<input id="tmpData" type="hidden"/>
<a id="downloadLink" href="javascript:downloadDoc()">文件下载</a>
</div>
<div id="canvas_list"></div>
前端js代码
pdf预览使用pdf.js插件,前端需要引入pdf.js文件
<script src="https://mozilla.github.io/pdf.js/build/pdf.js"></script>
var testFile = function() {
$.ajax({
url: "getFileContent",
type: "post",
data: '',
dataType: "json",
cache: false
})
.success(function(msg) {
var jsonArray = $.parseJSON(msg.custom);
var fileName = jsonArray.fileName;
var fileData = jsonArray.fileContent;
// 隐藏域,附件信息
$("#downloadLink").html(fileName);
$("#tmpData").val(fileData);
console.log(jsonArray);
console.log("---------------------");
//调用
showPdf1(fileData);
});
};
//base64字符串转array
var base64ToUint8Array = function(base64String) {
const padding = '='.repeat((4 - base64String.length % 4) % 4);
const base64 = (base64String + padding)
.replace(/-/g, '+')
.replace(/_/g, '/');
const rawData = window.atob(base64);
const outputArray = new Uint8Array(rawData.length);
for (let i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i);
}
return outputArray;
}
// pdf的base64数据解码预览
var showPdf1 = function(pdfData) {
//base64字符串解码
pdfData = atob(pdfData);
//通过脚本标签加载,创建pdf导出方式
var pdfjsLib = window['pdfjs-dist/build/pdf'];
//配置 workerSrc
pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://mozilla.github.io/pdf.js/build/pdf.worker.js';
var loadingTask = pdfjsLib.getDocument({data: pdfData});
loadingTask.promise.then(function(pdf) {
console.log('PDF loaded');
//总页数
var pageNums = pdf.numPages;
console.log(pageNums);
// 加载pdf页面数据
for (var pageNum = 1; pageNum <= pageNums; pageNum ++) {
renderPage(pdf, pageNum);
}
}, function (reason) {
// PDF loading error
console.error(reason);
});
};
//渲染pdf页面数据
var renderPage = function(pdfDoc, num) {
// Using promise to fetch the page
pdfDoc.getPage(num).then(function(page) {
var canvasList = document.getElementById('canvas_list');
var canvas = document.createElement('canvas');
canvasList.appendChild(canvas);
var scale = 1.5;
var viewport = page.getViewport({scale: scale});
// Prepare canvas using PDF page dimensions
//var canvas = document.getElementById('the-canvas');
var context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;
// Render PDF page into canvas context
var renderContext = {
canvasContext: context,
viewport: viewport
};
var renderTask = page.render(renderContext);
renderTask.promise.then(function () {
console.log('Page rendered');
});
});
}
// 下载文件方法
var downloadDoc = function() {
var fileName = $("#downloadLink").html();
var fileData = $("#tmpData").val();
var content = base64ToUint8Array(fileData);
var eleLink = document.createElement('a');
eleLink.download = fileName;
eleLink.style.display = 'none';
// 字符内容转变成blob地址
var blob = new Blob([content]);
eleLink.href = URL.createObjectURL(blob);
// 自动触发点击
document.body.appendChild(eleLink);
eleLink.click();
// 然后移除
document.body.removeChild(eleLink);
};
结果展示