java在线预览pdf文件或图片文件

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/q394895302/article/details/81326766

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

在页面中的代码如下:

<a onclick="show(show_attach?filePath="+path+"&type="+type+")">查看</a>

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和图片的在线打开;由于浏览器的差异,有些浏览器可能会弹出下载提示框。

猜你喜欢

转载自blog.csdn.net/q394895302/article/details/81326766
今日推荐