js部分
//
<div id="add_dialog" class="easyui-dialog" title=""
data-options="modal:true,closed:true,resizable:true,iconCls:'icon-save'"
style="width:750px;height:500px;">
</div>
//pdf预览
openPdf: function (id) {
$.ajax({
url:url,
type: "POST",
dataType: "binary",
data: {id: id},
headers: {Authorization: Authorization},
success: function (data, status, xhr) {
if (data) {
var headers = xhr.getAllResponseHeaders();
var contentDisposition = xhr.getResponseHeader("Content-Disposition");
var fileName = contentDisposition.substring(contentDisposition.indexOf("filename=") + 9);
if (fileName) {
fileName = decodeURIComponent(fileName);
const reader = new FileReader();
reader.readAsDataURL(data);
reader.onload = (e) => {
debugger;
$("#add_dialog").dialog({
title: '查看pdf',
width: 1000,
height: 600,
modal: true,
content: "<iframe scrolling='auto' frameborder='0' src='" + e.target.result + "' style='width:100%; height:100%; display:block;'></iframe>"
});
$("#add_dialog").dialog("open"); // 打开dialog
$('#add_dialog').window('center');//使Dialog居中显示
};
}
}
},
error: function (error) {
$.messager.show({
title: "提示",
msg: "error!",
timeout: 2000
});
console.log(error);
}
});
},
//jquery ajax请求二进制数据支持不完善。 dataType: “binary”,这块需要自定义xmlhttprequest方法,拓展二进制流方法
后台
@Override
public void downLoad(HttpServletResponse res) {
String path = "pdf文件地址";
try {
File file = new File(path);
if (file.exists()) {
//
FileInputStream fileInputStream = new FileInputStream(file);
res.setHeader("Connection", "close");
res.setHeader("Content-Type", "application/pdf;charset=UTF-8");
res.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(name, "UTF-8"));
BufferedInputStream bufferedInputStream = new BufferedInputStream(
fileInputStream);
byte[] b = new byte[bufferedInputStream.available()];
bufferedInputStream.read(b);
OutputStream outputStream = res.getOutputStream();
outputStream.write(b);
// 人走带门
bufferedInputStream.close();
outputStream.flush();
outputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}