struts2文件下载

来源:互联网 发布:非互联网公司的程序员 编辑:程序博客网 时间:2024/06/07 20:20

Action

package com.zdfd.elec.action.download;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.abin.core.service.GenericService;
import org.apache.catalina.connector.ClientAbortException;
import org.apache.struts2.ServletActionContext;

import com.zdfd.elec.action.BaseSearchAction;
import com.zdfd.elec.upload.UploadFile;

/**
 * 文件下载
 */
@SuppressWarnings("unchecked")
public class DownloadAction extends BaseSearchAction {
 private static final long serialVersionUID = 1L;
 private UploadFile uploadFile;
 private GenericService genericService;
 private String inputPath;
 private String contentType;
 private String filename;
 private Integer groupId;

 
 @Override
 public String execute() throws Exception {
  String groupId = ServletActionContext.getRequest().getParameter("id");
  if (groupId!=null && !"".equals(groupId)) {
   String searchTemplate = "FROM UploadFile uploadFile WHERE 1=1 AND groupId=" + groupId;
   searchComponent.addSearchElement("orderby.uploadFile.uploadTime", "DESC");
   List<UploadFile> list = (List<UploadFile>) genericService.searchForList(searchTemplate, searchComponent);
   this.result = list;
   ServletActionContext.getRequest().setAttribute("groupId", groupId);
   return "download";
  } else {
   return null;
  }
 }
 
 /**
  * 下载
  * @return
  */
 public String down() {
  InputStream inStream = null;
  ServletOutputStream outStream = null;
  try {
   String id = ServletActionContext.getRequest().getParameter("id");
   UploadFile data = genericService.get(UploadFile.class, Integer.valueOf(id));
         File file = new File(data.getSavePath());
         if (file!=null && file.exists()) {
          inStream = new FileInputStream(file);   
          HttpServletResponse response = ServletActionContext.getResponse();
          response.setContentType("application/octet-stream");
          response.setHeader("Content-Length", file.length()+"");
          response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(data.getRealName(), "utf-8"));
          outStream = response.getOutputStream();
          byte[] buffer = new byte[1024];
          int len = 0;
          while( (len = inStream.read(buffer)) != -1 ){
           outStream.write(buffer, 0, len);
          }
   } else {
    ServletActionContext.getResponse().setContentType("text/html; charset=UTF-8"); // 转码
    PrintWriter out = ServletActionContext.getResponse().getWriter();
    out.flush();
    out.println("<script>");
    out.println("alert('该文件已被删除!')");
    out.println("</script>");
     String searchTemplate = "FROM UploadFile uploadFile WHERE 1=1 AND groupId=" + data.getGroupId();
     searchComponent.addSearchElement("orderby.uploadFile.uploadTime", "DESC");
     List<UploadFile> list = (List<UploadFile>) genericService.searchForList(searchTemplate, searchComponent);
     this.result = list;
     ServletActionContext.getRequest().setAttribute("groupId", groupId);
     return "viewAttrFile";
   }
  } catch(ClientAbortException exception) {
  }
  catch (IOException e) {
   e.printStackTrace();
  } finally {
   if (inStream!=null) {
    try {
     inStream.close();
     if (outStream!=null) {
      outStream.close();
     }
    } catch (IOException e) {
     e.printStackTrace();
    }
    
   }
  }
        return null;
 }
 
 /**
  * 删除文件
  * @return
  * @throws Exception
  */
 public String delFile() throws Exception {
  String uploadFileId = ServletActionContext.getRequest().getParameter("id");
  UploadFile result = genericService.get(UploadFile.class, Integer.valueOf(uploadFileId));
  this.setGroupId(result.getGroupId());//取得当前删除文件的组ID
  genericService.delete(result);
  File file = new File(result.getSavePath());
  if (file!=null && file.exists() && file.canWrite()) {
   file.delete();
  }
  ServletActionContext.getResponse().setContentType("text/html; charset=UTF-8"); // 转码
  PrintWriter out = ServletActionContext.getResponse().getWriter();
  out.flush();
  out.println("<script>");
  out.println("alert('删除成功!');");
  out.println("</script>");
  
  String searchTemplate = "FROM UploadFile uploadFile WHERE 1=1 AND groupId=" + result.getGroupId();
  searchComponent.addSearchElement("orderby.uploadFile.uploadTime", "DESC");
  List<UploadFile> list = (List<UploadFile>) genericService.searchForList(searchTemplate, searchComponent);
  this.result = list;
  return "download";
 }

 /**
  * 查看附件
  * @return
  */
 public String viewAttrFile() {
  String groupId = ServletActionContext.getRequest().getParameter("id");
  if (groupId!=null && !"".equalsIgnoreCase(groupId)) {
   String searchTemplate = "FROM UploadFile uploadFile WHERE 1=1 AND groupId=" + groupId;
   searchComponent.addSearchElement("orderby.uploadFile.uploadTime", "DESC");
   List<UploadFile> list = (List<UploadFile>) genericService.searchForList(searchTemplate, searchComponent);
   this.result = list;
   return "viewAttrFile";
  } else {
   return null;
  }
 }
 
 /**
  * 获得文件的后缀名
  * @param str
  * @return
  */
 public String getExt(String str){     
  String subStr=str.substring(str.lastIndexOf("."));
  return subStr;
 }
 

 @Override
 public void resetCustomerSearchCriteria() {

 }

 

 public GenericService getGenericService() {
  return genericService;
 }


 public void setGenericService(GenericService genericService) {
  this.genericService = genericService;
 }


 public UploadFile getUploadFile() {
  return uploadFile;
 }


 public void setUploadFile(UploadFile uploadFile) {
  this.uploadFile = uploadFile;
 }


 public String getInputPath() {
  return inputPath;
 }


 public void setInputPath(String inputPath) {
  this.inputPath = inputPath;
 }


 public String getContentType() {
  return contentType;
 }


 public void setContentType(String contentType) {
  this.contentType = contentType;
 }


 public String getFilename() {
  return filename;
 }


 public void setFilename(String filename) {
  this.filename = filename;
 }

 public Integer getGroupId() {
  return groupId;
 }

 public void setGroupId(Integer groupId) {
  this.groupId = groupId;
 }

}

 

download.jsp下载和编辑附件页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<%@include file="/include/include.jsp" %>
<link rel="stylesheet" type="text/css" href="table.css">
<link type="text/css" rel="stylesheet" href="/elecSec/css/a.css"/>
<link rel="stylesheet" type="text/css" href="${ctx }/themes/default/easyui.css">
<link rel="stylesheet" type="text/css" href="${ctx }/themes/default/tree.css">
<link rel="stylesheet" type="text/css" href="${ctx }/themes/icon.css">
<link type="text/css" rel="StyleSheet" href="${ctx }/css/global.css">
<link rel="stylesheet" type="text/css" href="${ctx }/js/ext/resources/css/ext-all.css" />
<link rel="stylesheet" type="text/css" href="${ctx }/js/extchage.css" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>下载页面</title>
<script type="text/javascript">
/**
 * 定义列表中按钮的现实方式
 */
 Ext.onReady(function(){
  Ext.findTags('div', 'menu', function(o){
   Ext.initDropMenu(o, function(){
    if(Ext.inClass(this.tp, 'self')) {
     location.href=this.url;
    } else{
     var planid = this.pid;
     if(Ext.inClass(this.tp, 'callback')){
      parent.popWinOpen(this.url,'自查评',900,400,window,function (win){
       if(win==null ){
        return ;
       } else {
        window.location.href("${ctx}/download/download.action?id="+win);
       }
      } );
     } else{
      parent.popWinOpen(this.url, this.name,0,0,window);
     }
    }
   });
  });
 });


 //添加附件
 var i = 0;
 function addFile() {
  if(i > 9) {
   alert('已达到附件最大数');
   return;
  }
  var tabObj = document.getElementsByTagName("table")[1];
  var trObj = tabObj.insertRow();
  var tdObj1 = trObj.insertCell();
  var inputObj = document.createElement("input");
  tdObj1.setAttribute("colspan","2");
  inputObj.setAttribute("type", "file");
  inputObj.setAttribute("name", "upload");
  tdObj1.appendChild(inputObj);
  //var tdObj2 = trObj.insertCell();
  var imgObj = document.createElement("img");
  imgObj.src = "${ctx}/images/del.gif";
  imgObj.onclick = function(){
   //删除图片所在的行
   this.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode);
   i--;
  }
  tdObj1.appendChild(imgObj);
  i++;
 }
 
 //判断是否上传文件及文件类型是否合法
 function isFile() {
  var b = 0;
  var uploads = document.getElementsByName( "upload" ) ;
  var inputs = document.getElementsByTagName( "input" ) ;
  for( var i = 0 ; i < inputs.length ; i++ ){
   if(inputs[i].value!=null && inputs[i].value.length > 0) {
     b = 1;
     break;
    }
   }
  if(b==0) {
   alert('您没有选择要上传的文件');
   return false;
  }
  for( var i = 0 ; i < inputs.length ; i++ ){
   if(inputs[i].value!=null && inputs[i].value.length > 0) {
    var fileFullPath = inputs[i].value;
    var b = fileFullPath.indexOf(".bat");
    var w = fileFullPath.indexOf(".exe");
    if(b!=-1 || w!=-1) {
     var myregex=new RegExp(".exe");//创建正则表达式
     if(myregex.test(fileFullPath.substr(b)) || myregex.test(fileFullPath.substr(w))){//判断条件是否成立
      alert("文件格式不合法");
      return false;
     }
    }
   }
  }
   return true;
 }
</script>
</head>
<body>
 <div class="content">
  <div class="control">
   <table cellpadding="0" cellspacing="1" class="tb1">
    <tr>
     <td>
      <c:forEach items="${result }" var="uploadFile">
       <img src="${ctx }/${uploadFile.icon }" />
       <a href="${ctx }/download/download!down.action?id=${uploadFile.id }">${fn:substring(uploadFile.realName,0,fn:indexOf(uploadFile.realName,".")) }</a>
       <a href="${ctx }/download/download!delFile.action?id=${uploadFile.id }" onclick="return confirm('确定要删除吗?')" >
        <img alt="删除" src="${ctx }/images/delx.gif">
       </a>
       &nbsp;&nbsp;&nbsp;
      </c:forEach>
     </td>
    </tr>
    <tr>
     <td>
      <form action="${ctx }/upload/upload!doUpload.action" onsubmit="return isFile()" enctype="multipart/form-data" method="post" >
        <input type="hidden" value="${groupId }" name="id">
        <table cellpadding="0" cellspacing="1" class="tb1" width="150">
         <tr>
          <th colspan="2">
           请选择要上传的文件(*注意:不能上传.bat和.exe文件)
          </th>
         </tr>
        <tr>
         <td width="70%" colspan="2">
          <button type="button" onclick="addFile()" class='bgbtn'>添加附件</button>
         </td>
        </tr>
        <tr>
         <td width="70%" colspan="2">
          <input type="file" name="upload" />
         </td>
        </tr>
       </table>
       <button type="submit" class='bgbtn'>上传附件</button>
      </form>     
     </td>
    </tr>  
   </table>
   <center>
    <input type="button" class='bgbtn' onclick="parent.popCallbackClose(${groupId});" value="关闭" />
   </center> 
   </div>
 </div>
</body>
</html>

 

 

仅查看附件页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<%@include file="/include/include.jsp" %>
<link rel="stylesheet" type="text/css" href="table.css">
<link type="text/css" rel="stylesheet" href="/elecSec/css/a.css"/>
<link rel="stylesheet" type="text/css" href="${ctx }/themes/default/easyui.css">
<link rel="stylesheet" type="text/css" href="${ctx }/themes/default/tree.css">
<link rel="stylesheet" type="text/css" href="${ctx }/themes/icon.css">
<link type="text/css" rel="StyleSheet" href="${ctx }/css/global.css">
<link type="text/css" rel="StyleSheet" href="${ctx }/css/style.css">
<link rel="stylesheet" type="text/css" href="${ctx }/js/ext/resources/css/ext-all.css" />
<link rel="stylesheet" type="text/css" href="${ctx }/js/extchage.css" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>查看附件页面</title>
</head>
<body style="background-color: #E5F2F3">
 <div class="content">
  <div class="control">
   <table cellpadding="0" cellspacing="1" class="tb1">
    <tr>
     <td>
      <c:forEach items="${result }" var="uploadFile" varStatus="status" >
       ${status.count }.<img src="${ctx }/${uploadFile.icon }" />
       <a href="${ctx }/download/download!down.action?id=${uploadFile.id }">${fn:substring(uploadFile.realName,0,fn:indexOf(uploadFile.realName,".")) }</a>
       <br>
      </c:forEach>
     </td>
    </tr>
   </table>
   </div>
 </div>

</body>
</html>