strutsはファイルのアップロードとダウンロードを実現する


package com.css.action;

import java.io.FileInputStream;
import java.io.InputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.BufferedOutputStream;
import java.io.BufferedInputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.*;
import org.apache.struts.validator.DynaValidatorForm;

import com.css.bean.FileInfoDTO;
import com.css.dao.DAOFactory;
import com.css.dao.FileInfoDAO;
import com.css.exception.BaseException;
import com.css.util.db.DBConfig;
import com.css.bean.UserDTO;

/**
* @author WANG
* 
* Java -      -     
*/
public class FileUploadAction extends BaseAction {

      public ActionForward fileUpload(ActionMapping mapping, ActionForm form,
              HttpServletRequest request, HttpServletResponse response)
              throws BaseException {

          //      gb2312
          /*
           * String encoding = request.getCharacterEncoding(); if ((encoding !=
           * null) && (encoding.equalsIgnoreCase("utf-8"))) {
           * //        ,     gb2312 response.setCon*("text/html; charset=gb2312"); }
           */

          //  DynaValidatorForm  ,  theFile.get("FileUploadForm")       
          DynaValidatorForm fileUploadForm = (DynaValidatorForm) form;
          FormFile file = null;
          file = (FormFile) fileUploadForm.get("theFile");
          String describe = fileUploadForm.getString("describe");
          String permit = fileUploadForm.getString("permit");

          //              ,      download.vm--FileUpload.do?act=showFile
          UserDTO userDTO = getSessionObj(request);
          if (userDTO == null) {
              this.setSysMessage(request, "login.failAdmin", "btn.readmin",
                      "FileUpload.do?act=showFile");
              return mapping.findForward("error");
          }
        
          //  FormFile   fileName      
          String fileName = file.getFileName();//     
        
          //          
          if(!isValidFile(fileName))
          {
              this.setSysMessage(request, "upload.badtype", "btn.reupload",
              "FileUpload.do?act=gotoUpload");
              return mapping.findForward("error");
          }
          int fileSize = file.getFileSize();//      

          //  getInputStream()       
          BufferedInputStream bis = null;
          BufferedOutputStream bos = null;
          InputStream is = null;
          OutputStream fos = null;

          try {
              is = (InputStream) file.getInputStream();//     
              bis = new BufferedInputStream(is);
              String filePath = getUploadDir();//       
              fos = new FileOutputStream(filePath + fileName);//            
              bos = new BufferedOutputStream(fos);
              //System.out.println(filePath + fileName);

              //      
              int fileMaxSize = 10 * 1024 * 1024;

              if (fileSize > fileMaxSize) {
                  //        fileMaxSize,    , "        10M"  ;
                  this.setSysMessage(request, "upload.max", "btn.reupload",
                          "FileUpload.do?act=gotoUpload");
                  return mapping.findForward("error");
              }
              int bytesRead = 0;
              byte[] buffer = new byte[5 * 1024];
              while ((bytesRead = bis.read(buffer)) != -1) {
                  bos.write(buffer, 0, bytesRead);//        
              }
          }
          catch (IOException e) {
              //                     
              this.setSysMessage(request, "upload.failed", "btn.reupload",
                      "FileUpload.do?act=gotoUpload");
              return mapping.findForward("error");
          }
          finally {
              if (bos != null) {

                  try {
                      bos.close();
                  }
                  catch (IOException e) {
                      System.err.print(e);
                  }
              }
              if (bis != null) {
                  try {
                      bis.close();
                  }
                  catch (IOException e) {
                      System.err.print(e);
                  }
              }

          }
          //        
          //           
          //  FileInfoDTO
          FileInfoDTO dto = new FileInfoDTO();
          dto.setCheckType("1");
          dto.setDescribe(describe);
          dto.setFileName(fileName);
          dto.setFileSize(String.valueOf(fileSize));
          dto.setIsUse("0");
          dto.setPermit(permit);
          dto.setUserID(userDTO.getUserId());

          FileInfoDAO fileinfoDAO = (FileInfoDAO) DAOFactory.getDAOFactory(
                  DBConfig.getDataBaseName()).getFileInfoDAO();
          int result = fileinfoDAO.insert(dto);
          //request.setAttribute("dat",file.getFileName());
          if (result > 0) {
              return mapping.findForward("gotoUpload");
          }
          else {
              //               
              this.setSysMessage(request, "upload.failed", "btn.reupload",
                      "FileUpload.do?act=gotoUpload");
              return mapping.findForward("error");
          }
      }

      public ActionForward fileDownLoad(ActionMapping mapping, ActionForm form,
              HttpServletRequest request, HttpServletResponse response)
              throws BaseException {
          /*
           *     :  id+    +   +    id=  formbean       =             
           *     =         =io
           */
          //      ,             
          String fileID = null;//  id
          String filePath = null;//      
          String fileName = null;//  
          String permit = null; //  ,       

          BufferedInputStream bis = null;
          BufferedOutputStream bos = null;
          OutputStream fos = null;
          InputStream fis = null;

          //          DynaValidatorForm fileUploadForm = (DynaValidatorForm) form;
          //          fileID = fileUploadForm.getString("fileID");//    id
          fileID = request.getParameter("fileID");
          filePath = getUploadDir();
          FileInfoDAO fileinfoDAO = (FileInfoDAO) DAOFactory.getDAOFactory(
                  DBConfig.getDataBaseName()).getFileInfoDAO();

        
          FileInfoDTO fileInfoDTO = fileinfoDAO.findByPK(fileID);
          if(fileInfoDTO == null)
          {
              this.setSysMessage(request, "download.failed", "btn.redownload",
              "FileUpload.do?act=showFile");
              return mapping.findForward("error");
          }
          fileName = fileInfoDTO.getFileName();
          permit = fileInfoDTO.getPermit();
        
          //    
          UserDTO userDTO = this.getSessionObj(request);
          if(userDTO == null)
          {
              this.setSysMessage(request, "login.failAdmin", "btn.redownload",
              "FileUpload.do?act=showFile");
              return mapping.findForward("error");
          }
          else if(!userDTO.getUserType().equals(fileInfoDTO.getPermit()))
          {
              this.setSysMessage(request, "login.failAdmin", "btn.redownload",
              "FileUpload.do?act=showFile");
              return mapping.findForward("error");
          }
          if (fileName == null) {
              //              
              this.setSysMessage(request, "download.failed", "btn.redownload",
                      "FileUpload.do?act=showFile");
              return mapping.findForward("error");
          }

          try {
              response.setContentType(this.getContentType(fileName));
              response.setHeader("Content-disposition", "attachment;filename="
                      + URLEncoder.encode(fileName, "utf-8"));
              fis = new FileInputStream(filePath + fileName);
              bis = new BufferedInputStream(fis);
              fos = response.getOutputStream();
              bos = new BufferedOutputStream(fos);

              int bytesRead = 0;
              byte[] buffer = new byte[5 * 1024];
              while ((bytesRead = bis.read(buffer)) != -1) {
                  bos.write(buffer, 0, bytesRead);//         
              }
          }
          catch (IOException e) {
//              response.setContentType("text/html");
              response.reset();
              //                
              this.setSysMessage(request, "download.failed", "btn.reupload",
                      "FileUpload.do?act=showFile");
              return mapping.findForward("error");
          }
          finally {
              try {
                  if (fos != null) {
                      fos.close();
                  }
                  if (bos != null) {
                      bos.close();
                  }
                  if (fis != null) {
                      fis.close();
                  }
                  if (bis != null) {
                      bis.close();
                  }
              }
              catch (IOException e) {

                  System.err.print(e);
              }
          }

          return null;
      }

      public ActionForward showFile(ActionMapping mapping, ActionForm form,
              HttpServletRequest request, HttpServletResponse response)
              throws BaseException {
          /*
           *        ,                              
           */
          UserDTO userDTO = getSessionObj(request);
          boolean isLogin = true;
          boolean isCheck = false;
          String userType = null;
          if (userDTO == null) {
              isLogin = false;
          }
          else {
              if (userDTO.getIsCheck().equals("1")) {
                  isCheck = true;
              }
          }
          /*
           *      ,      ,      permit,  4(    )     ,    List    request     .
           */

          //     
          FileInfoDAO fileinfoDAO = (FileInfoDAO) DAOFactory.getDAOFactory(
                  DBConfig.getDataBaseName()).getFileInfoDAO();

          //         List   .

          List list = new ArrayList();
          // FILEINFO  USERS               FileInfoDTO .

          //       :isCheck=ture=    ,isLogin=          ,  。     。
          if (isCheck) {
              list = fileinfoDAO.findAll();
          }
          else {
              if(isLogin)
              {
                  userType = userDTO.getUserType();
                  list = fileinfoDAO.findAll(userType, isLogin);
              }
              else
              {
                  userType = "4";
                  list = fileinfoDAO.findAll(userType, isLogin);
              }
          }
          //      request 
          request.setAttribute("fileList", list);
          request.setAttribute("userDTO", userDTO);
          return mapping.findForward("fileDownload");
      }

      public ActionForward gotoUpload(ActionMapping mapping, ActionForm form,
              HttpServletRequest request, HttpServletResponse response)
              throws BaseException {
          //          upload.vm
          UserDTO userDTO = getSessionObj(request);
          if (userDTO == null) {
              //              ,      download.vm--FileUpload.do?act=showFile
              this.setSysMessage(request, "login.failAdmin", "btn.redownload",
                      "FileUpload.do?act=showFile");
              return mapping.findForward("error");
          }

          return mapping.findForward("fileUpload");
      }

      private boolean isValidFile(String fileName) {
          String[] validFiles = { "txt", "gif", "jpg", "jpeg", "jpe", "zip",
                  "rar", "doc", "ppt", "xls", "html", "htm", "tif", "tiff", "pdf" };
          boolean ret = false;
          for (int i = 0; i < validFiles.length; i++) {
              if (fileName.toLowerCase().endsWith(validFiles[i])) {
                  ret = true;
                  break;
              }
          }
          return ret;
      }

      private String getContentType(String fileName) {
          String fileNameTmp = fileName.toLowerCase();
          String ret = "";
          if (fileNameTmp.endsWith("txt")) {
              ret = "text/plain";
          }
          if (fileNameTmp.endsWith("gif")) {
              ret = "image/gif";
          }
          if (fileNameTmp.endsWith("jpg")) {
              ret = "image/jpeg";
          }
          if (fileNameTmp.endsWith("jpeg")) {
              ret = "image/jpeg";
          }
          if (fileNameTmp.endsWith("jpe")) {
              ret = "image/jpeg";
          }
          if (fileNameTmp.endsWith("zip")) {
              ret = "application/zip";
          }
          if (fileNameTmp.endsWith("rar")) {
              ret = "application/rar";
          }
          if (fileNameTmp.endsWith("doc")) {
              ret = "application/msword";
          }
          if (fileNameTmp.endsWith("ppt")) {
              ret = "application/vnd.ms-powerpoint";
          }
          if (fileNameTmp.endsWith("xls")) {
              ret = "application/vnd.ms-excel";
          }
          if (fileNameTmp.endsWith("html")) {
              ret = "text/html";
          }
          if (fileNameTmp.endsWith("htm")) {
              ret = "text/html";
          }
          if (fileNameTmp.endsWith("tif")) {
              ret = "image/tiff";
          }
          if (fileNameTmp.endsWith("tiff")) {
              ret = "image/tiff";
          }
          if (fileNameTmp.endsWith("pdf")) {
              ret = "application/pdf";
          }
          return ret;
      }
}