web项目附件针对格式不同的文件进行处理

文件读取与类型处理
/**
	 * 管理附件的方法,pdf采用在线打开方式。office直接下载 
	 * 2017.7.26 sp
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward readFile(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		ISfileAttachService iSfileAttachService = (ISfileAttachService) this.getService("sfileAttachService");
		HttpSession session = request.getSession();
		String path = session.getServletContext().getRealPath("");  //项目路径
		String pathUrl = session.getServletContext().getRealPath(Constants.getProperty("uploadPath"));  // 上传目录
		String file_id = request.getParameter("FileId"); // 根据附件id进行文件查询
		String filePath="";
		File file = null;
		if (!C.isNull(file_id) && !"".equals(file_id)) {
			SfileAttach isfileattach = (SfileAttach) iSfileAttachService.findByPrimaryKey(file_id);
			if (!C.isNull(isfileattach)) {
				
				if (isfileattach.getFileNameO().contains(".pdf") || isfileattach.getFileNameO().contains(".PDF")) {  // 附件类型为pdf的直接在线打开
					response.setContentType("application/pdf"); // 标识反馈的页面为pdf
					file = new File(path + "/" + isfileattach.getFilePath());
					if (file.exists() && file.isFile()) {
						filePath = path + "/" + isfileattach.getFilePath();
					}else{
						filePath = pathUrl + "/notfile.pdf"; // 文件没找到默认打开文件不存在的那个pdf文件
					}
				}else{  // 其他文件采用下载的方式
					response.setHeader("Content-Disposition", "attachment; filename="+ new String(isfileattach.getFileNameO().getBytes("GBK"),"ISO8859-1"));
					file = new File(path + "/" + isfileattach.getFilePath());
					if (file.exists() && file.isFile()) {
						filePath = path + "/" + isfileattach.getFilePath();  // 附件存在
					}else{
						filePath = "";  //附件不存在
					}
				}
			}
			ServletOutputStream sos = response.getOutputStream();
			
			if (!C.isNull(filePath) && !"".equals(filePath)) {  // 路径不为空文件存在时再进行输出
				FileInputStream in = new FileInputStream(filePath);
				byte data[] = new byte[1024];

				int len = 0;
				while ((len = in.read(data)) != -1) {
					sos.write(data, 0, len);
				}
				sos.flush(); // 关闭流操作
				in.close();
				sos.close();
			}
		}
		return null;
	}

转载于:https://my.oschina.net/yolks/blog/1527630

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值