java里预览pdf 工具_java 在线预览pdf

本文介绍了在Java项目中如何实现PDF和图片的在线预览功能。通过前端页面调用JavaScript函数,结合后端Java代码处理请求,设置相应的内容类型,读取文件并输出到响应流中,从而达到预览效果。尽管不同浏览器可能有不同的显示行为,但基本实现了预览需求。
摘要由CSDN通过智能技术生成

在项目中需要使用到在线浏览文件功能,由于项目中只能上传pdf和图片文件,所有就只做了预览pdf和图片的功能。

在页面中的代码如下:

查看

path:是文件存放在服务器上的位置

type:是文件的类型

js中也就只有一个打开新页面的功能,代码如下:function show(location){

window.open(location);

}

java后台处理代码如下:@RequestMapping(value="/show_attach",method=RequestMethod.GET,produces = "application/json;charset=UTF-8")

public void show_attach(HttpServletRequest request,HttpServletResponse response){

FileInputStream bis = null;

OutputStream os = null;

try {

String path = request.getParameter("filePath");//网络图片地址

response.setContentType("text/html; charset=UTF-8");

String type = request.getParameter("type");

if("pdf".equalsIgnoreCase(type)){

response.setContentType("application/pdf");

}else{

response.setContentType("image/"+type);

}

bis = new FileInputStream(path);

os = response.getOutputStream();

int count = 0;

byte[] buffer = new byte[1024 * 1024];

while ((count =bis.read(buffer)) != -1){

os.write(buffer, 0,count);

}

os.flush();

}catch (Exception e) {

e.printStackTrace();

} finally {

if (os !=null){

try {

os.close();

} catch (IOException e) {

e.printStackTrace();

}

}

if (bis !=null){

try {

bis.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

}

以上就完成了对pdf和图片的在线打开;由于浏览器的差异,有些浏览器可能会弹出下载提示框。

该博客来源于https://blog.csdn.net/q394895302/article/details/81326766,pdf已经验证

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值