您的位置:首页 > 其它

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

2017-09-01 00:00 399 查看
/**
* 管理附件的方法,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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐