解决预览pdf不能下载的问题

  • Post author:
  • Post category:其他


1.背景

最近在开发A系统归档的数据要传入B系统,在B系统生成PDF文件。之后要在A系统预览并下载。

2.问题

1.文件名不能回填

2.保存类型没有pdf

3.解决

 /**
     * 实现资产系统通过接口方式
     *                PDF预览
     * @author chenf
     */
    @RequestMapping(value = "/sign-process/queryFile", method = RequestMethod.GET)
    public RestfulResult queryFile(String assetUrl,
    		HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException 
    {   	
    	String param = assetUrl;
    	param = URLDecoder.decode(URLDecoder.decode(param, "utf-8"),"utf-8");
    	param = StringEscapeUtil.encode(param);
    	OutputStream out = null;
    	RestfulResult result = new RestfulResult();
    	try 
    	{
    		out = response.getOutputStream();
    		// 执行业务
    		this.signAssetservice.getAssetFile(request,response,param,out);
    		return null;
    	} catch (Exception e) 
    	{
    		log.setState("错误");
    		log.setDescribe(e.toString());
    		logManage.addLog(log);
    		result.setCode(RestfulResult.ERROR_CODE);
			result.setMsg(log.getDescribe());
			return result;
    	}finally 
    	{
			try
			{
				if(out != null)
				{
					out.close();
				}
			} catch (IOException e)
			{
				e.printStackTrace();
			}
    	}
    }
	
	
	@Override
	public void getAssetFile(HttpServletRequest request,HttpServletResponse response,String param,OutputStream out) {
		FileInputStream in = null;
		String fileurl = null;
		fileurl = param;
		
		try {
			File file = new File(fileurl);
			String fileName = file.getName();
			//中文兼容火狐浏览器
			if (request.getHeader("User-Agent").toLowerCase().indexOf("firefox") > 0) {
				downShowName = "=?UTF-8?B?"+(new String(Base64.encode(fileName.getBytes("UTF-8")))) + "?=";
			} else {
				downShowName = java.net.URLEncoder.encode(fileName,"UTF-8");
			}
			response.setContentType("application/pdf");//告诉浏览器输出内容为pdf
			response.setHeader("Content-Disposition", "inline;filename="+downShowName);//inline显示|attachment下载
			in = new FileInputStream(file);
			byte[] date = new byte[in.available()];//获取文件的大小
			in.read(date);//以字节流的形式读取文件
			out.write(date);
		}catch (Exception e) {
			throw new RuntimeException(e.toString());
		}finally {
			if(in!=null){
				try
				{
					in.close();
				} catch (IOException e)
				{
					e.printStackTrace();
				}
			}
		}
	}



版权声明:本文为cf082430原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。