struts实现上传下载代码

  1. package com.css.action;   
  2.   
  3. import java.io.FileInputStream;   
  4. import java.io.InputStream;   
  5. import java.io.FileOutputStream;   
  6. import java.io.IOException;   
  7. import java.io.BufferedOutputStream;   
  8. import java.io.BufferedInputStream;   
  9. import java.io.OutputStream;   
  10. import java.net.URLEncoder;   
  11. import java.util.List;   
  12. import java.util.ArrayList;   
  13.   
  14. import javax.servlet.http.HttpServletRequest;   
  15. import javax.servlet.http.HttpServletResponse;   
  16.   
  17. import org.apache.struts.action.ActionForm;   
  18. import org.apache.struts.action.ActionForward;   
  19. import org.apache.struts.action.ActionMapping;   
  20. import org.apache.struts.upload.*;   
  21. import org.apache.struts.validator.DynaValidatorForm;   
  22.   
  23. import com.css.bean.FileInfoDTO;   
  24. import com.css.dao.DAOFactory;   
  25. import com.css.dao.FileInfoDAO;   
  26. import com.css.exception.BaseException;   
  27. import com.css.util.db.DBConfig;   
  28. import com.css.bean.UserDTO;   
  29.   
  30. /**  
  31. * @author WANG  
  32. *   
  33. * Java  代码样式  代码模板  
  34. */  
  35. public class FileUploadAction extends BaseAction {   
  36.   
  37.       public ActionForward fileUpload(ActionMapping mapping, ActionForm form,   
  38.               HttpServletRequest request, HttpServletResponse response)   
  39.               throws BaseException {   
  40.   
  41.           //将字符统一为gb2312   
  42.           /*  
  43.            * String encoding = request.getCharacterEncoding(); if ((encoding !=  
  44.            * null) && (encoding.equalsIgnoreCase("utf-8"))) {  
  45.            * //如果没有指定编码,编码格式为gb2312 response.setCon*("text/html; charset=gb2312"); }  
  46.            */  
  47.   
  48.           //取得DynaValidatorForm的值,通过theFile.get("FileUploadForm")取得上传的文件   
  49.           DynaValidatorForm fileUploadForm = (DynaValidatorForm) form;   
  50.           FormFile file = null;   
  51.           file = (FormFile) fileUploadForm.get("theFile");   
  52.           String describe = fileUploadForm.getString("describe");   
  53.           String permit = fileUploadForm.getString("permit");   
  54.   
  55.           //设置用户权限不足时出现的错误,用户将跳转到download.vm--FileUpload.do?act=showFile   
  56.           UserDTO userDTO = getSessionObj(request);   
  57.           if (userDTO == null) {   
  58.               this.setSysMessage(request, "login.failAdmin", "btn.readmin",   
  59.                       "FileUpload.do?act=showFile");   
  60.               return mapping.findForward("error");   
  61.           }   
  62.            
  63.           //获取FormFile的实例fileName中的两个属性   
  64.           String fileName = file.getFileName();//取得文件名   
  65.            
  66.           //测试该文件是不是合法   
  67.           if(!isValidFile(fileName))   
  68.           {   
  69.               this.setSysMessage(request, "upload.badtype", "btn.reupload",   
  70.               "FileUpload.do?act=gotoUpload");   
  71.               return mapping.findForward("error");   
  72.           }   
  73.           int fileSize = file.getFileSize();//取得文件尺寸   
  74.   
  75.           //通过getInputStream()方法取得文件流   
  76.           BufferedInputStream bis = null;   
  77.           BufferedOutputStream bos = null;   
  78.           InputStream is = null;   
  79.           OutputStream fos = null;   
  80.   
  81.           try {   
  82.               is = (InputStream) file.getInputStream();//把文件读入   
  83.               bis = new BufferedInputStream(is);   
  84.               String filePath = getUploadDir();//取当前系统路径   
  85.               fos = new FileOutputStream(filePath + fileName);//建立一个上传文件的输出流   
  86.               bos = new BufferedOutputStream(fos);   
  87.               //System.out.println(filePath + fileName);   
  88.   
  89.               //文件最大限额   
  90.               int fileMaxSize = 10 * 1024 * 1024;   
  91.   
  92.               if (fileSize > fileMaxSize) {   
  93.                   //文件大小不能超过fileMaxSize,如果超过,报"上传文件尺寸超过10M"错误;   
  94.                   this.setSysMessage(request, "upload.max", "btn.reupload",   
  95.                           "FileUpload.do?act=gotoUpload");   
  96.                   return mapping.findForward("error");   
  97.               }   
  98.               int bytesRead = 0;   
  99.               byte[] buffer = new byte[5 * 1024];   
  100.               while ((bytesRead = bis.read(buffer)) != -1) {   
  101.                   bos.write(buffer, 0, bytesRead);//将文件写入服务器   
  102.               }   
  103.           }   
  104.           catch (IOException e) {   
  105.               //设置文件物理上传出现问题时的出现的错误信息   
  106.               this.setSysMessage(request, "upload.failed", "btn.reupload",   
  107.                       "FileUpload.do?act=gotoUpload");   
  108.               return mapping.findForward("error");   
  109.           }   
  110.           finally {   
  111.               if (bos != null) {   
  112.   
  113.                   try {   
  114.                       bos.close();   
  115.                   }   
  116.                   catch (IOException e) {   
  117.                       System.err.print(e);   
  118.                   }   
  119.               }   
  120.               if (bis != null) {   
  121.                   try {   
  122.                       bis.close();   
  123.                   }   
  124.                   catch (IOException e) {   
  125.                       System.err.print(e);   
  126.                   }   
  127.               }   
  128.   
  129.           }   
  130.           //文件物理上传完成   
  131.           //将文件信息添加到数据库   
  132.           //填充FileInfoDTO   
  133.           FileInfoDTO dto = new FileInfoDTO();   
  134.           dto.setCheckType("1");   
  135.           dto.setDescribe(describe);   
  136.           dto.setFileName(fileName);   
  137.           dto.setFileSize(String.valueOf(fileSize));   
  138.           dto.setIsUse("0");   
  139.           dto.setPermit(permit);   
  140.           dto.setUserID(userDTO.getUserId());   
  141.   
  142.           FileInfoDAO fileinfoDAO = (FileInfoDAO) DAOFactory.getDAOFactory(   
  143.                   DBConfig.getDataBaseName()).getFileInfoDAO();   
  144.           int result = fileinfoDAO.insert(dto);   
  145.           //request.setAttribute("dat",file.getFileName());   
  146.           if (result > 0) {   
  147.               return mapping.findForward("gotoUpload");   
  148.           }   
  149.           else {   
  150.               //设置文件写入数据库时出现的信息   
  151.               this.setSysMessage(request, "upload.failed", "btn.reupload",   
  152.                       "FileUpload.do?act=gotoUpload");   
  153.               return mapping.findForward("error");   
  154.           }   
  155.       }   
  156.   
  157.       public ActionForward fileDownLoad(ActionMapping mapping, ActionForm form,   
  158.               HttpServletRequest request, HttpServletResponse response)   
  159.               throws BaseException {   
  160.           /*  
  161.            * 取得文件:文件id+文件路径+文件名+ 文件id=通过formbean取得 文件路径=通过取得配置文件的方法得到  
  162.            * 文件名称=通过数据库得到 =io  
  163.            */  
  164.           //取得文件路径,也就是保存文件的文件夹名称   
  165.           String fileID = null;//文件id   
  166.           String filePath = null;//方法取得路径   
  167.           String fileName = null;//名称   
  168.           String permit = null; //权限,用来作身份验证   
  169.   
  170.           BufferedInputStream bis = null;   
  171.           BufferedOutputStream bos = null;   
  172.           OutputStream fos = null;   
  173.           InputStream fis = null;   
  174.   
  175.           //          DynaValidatorForm fileUploadForm = (DynaValidatorForm) form;   
  176.           //          fileID = fileUploadForm.getString("fileID");//得到文件id   
  177.           fileID = request.getParameter("fileID");   
  178.           filePath = getUploadDir();   
  179.           FileInfoDAO fileinfoDAO = (FileInfoDAO) DAOFactory.getDAOFactory(   
  180.                   DBConfig.getDataBaseName()).getFileInfoDAO();   
  181.   
  182.            
  183.           FileInfoDTO fileInfoDTO = fileinfoDAO.findByPK(fileID);   
  184.           if(fileInfoDTO == null)   
  185.           {   
  186.               this.setSysMessage(request, "download.failed", "btn.redownload",   
  187.               "FileUpload.do?act=showFile");   
  188.               return mapping.findForward("error");   
  189.           }   
  190.           fileName = fileInfoDTO.getFileName();   
  191.           permit = fileInfoDTO.getPermit();   
  192.            
  193.           //身份验证   
  194.           UserDTO userDTO = this.getSessionObj(request);   
  195.           if(userDTO == null)   
  196.           {   
  197.               this.setSysMessage(request, "login.failAdmin", "btn.redownload",   
  198.               "FileUpload.do?act=showFile");   
  199.               return mapping.findForward("error");   
  200.           }   
  201.           else if(!userDTO.getUserType().equals(fileInfoDTO.getPermit()))   
  202.           {   
  203.               this.setSysMessage(request, "login.failAdmin", "btn.redownload",   
  204.               "FileUpload.do?act=showFile");   
  205.               return mapping.findForward("error");   
  206.           }   
  207.           if (fileName == null) {   
  208.               //设置查找数据时出现的错误信息   
  209.               this.setSysMessage(request, "download.failed", "btn.redownload",   
  210.                       "FileUpload.do?act=showFile");   
  211.               return mapping.findForward("error");   
  212.           }   
  213.   
  214.           try {   
  215.               response.setContentType(this.getContentType(fileName));   
  216.               response.setHeader("Content-disposition", "attachment;filename="  
  217.                       + URLEncoder.encode(fileName, "utf-8"));   
  218.               fis = new FileInputStream(filePath + fileName);   
  219.               bis = new BufferedInputStream(fis);   
  220.               fos = response.getOutputStream();   
  221.               bos = new BufferedOutputStream(fos);   
  222.   
  223.               int bytesRead = 0;   
  224.               byte[] buffer = new byte[5 * 1024];   
  225.               while ((bytesRead = bis.read(buffer)) != -1) {   
  226.                   bos.write(buffer, 0, bytesRead);//将文件发送到客户端   
  227.               }   
  228.           }   
  229.           catch (IOException e) {   
  230. //              response.setContentType("text/html");   
  231.               response.reset();   
  232.               //设置文件物理下载时出现的错误信息   
  233.               this.setSysMessage(request, "download.failed", "btn.reupload",   
  234.                       "FileUpload.do?act=showFile");   
  235.               return mapping.findForward("error");   
  236.           }   
  237.           finally {   
  238.               try {   
  239.                   if (fos != null) {   
  240.                       fos.close();   
  241.                   }   
  242.                   if (bos != null) {   
  243.                       bos.close();   
  244.                   }   
  245.                   if (fis != null) {   
  246.                       fis.close();   
  247.                   }   
  248.                   if (bis != null) {   
  249.                       bis.close();   
  250.                   }   
  251.               }   
  252.               catch (IOException e) {   
  253.   
  254.                   System.err.print(e);   
  255.               }   
  256.           }   
  257.   
  258.           return null;   
  259.       }   
  260.   
  261.       public ActionForward showFile(ActionMapping mapping, ActionForm form,   
  262.               HttpServletRequest request, HttpServletResponse response)   
  263.               throws BaseException {   
  264.           /*  
  265.            * 用户下载的方法, 用户可以看到和下载和自己权限一样的文件和所有游客权限的文件  
  266.            */  
  267.           UserDTO userDTO = getSessionObj(request);   
  268.           boolean isLogin = true;   
  269.           boolean isCheck = false;   
  270.           String userType = null;   
  271.           if (userDTO == null) {   
  272.               isLogin = false;   
  273.           }   
  274.           else {   
  275.               if (userDTO.getIsCheck().equals("1")) {   
  276.                   isCheck = true;   
  277.               }   
  278.           }   
  279.           /*  
  280.            * 获取权限后, 连接数据库, 查找权限为permit,以及4(游客权限)的所有权限, 并生成List对象通过request发送给客户.  
  281.            */  
  282.   
  283.           //连接数据库   
  284.           FileInfoDAO fileinfoDAO = (FileInfoDAO) DAOFactory.getDAOFactory(   
  285.                   DBConfig.getDataBaseName()).getFileInfoDAO();   
  286.   
  287.           //查找并将数据保存在List对象中.   
  288.   
  289.           List list = new ArrayList();   
  290.           //FILEINFO表和USERS表中查找需要的数据存放在每一个FileInfoDTO.   
  291.   
  292.           //判断用户的权限:isCheck=ture=审核人员,isLogin=内部用户或者外部用户,客户。其他为游客。   
  293.           if (isCheck) {   
  294.               list = fileinfoDAO.findAll();   
  295.           }   
  296.           else {   
  297.               if(isLogin)   
  298.               {   
  299.                   userType = userDTO.getUserType();   
  300.                   list = fileinfoDAO.findAll(userType, isLogin);   
  301.               }   
  302.               else  
  303.               {   
  304.                   userType = "4";   
  305.                   list = fileinfoDAO.findAll(userType, isLogin);   
  306.               }   
  307.           }   
  308.           //将数据保存在request   
  309.           request.setAttribute("fileList", list);   
  310.           request.setAttribute("userDTO", userDTO);   
  311.           return mapping.findForward("fileDownload");   
  312.       }   
  313.   
  314.       public ActionForward gotoUpload(ActionMapping mapping, ActionForm form,   
  315.               HttpServletRequest request, HttpServletResponse response)   
  316.               throws BaseException {   
  317.           //用户通过此方法跳转到upload.vm   
  318.           UserDTO userDTO = getSessionObj(request);   
  319.           if (userDTO == null) {   
  320.               //设置用户权限不足时出现的错误,用户将跳转到download.vm--FileUpload.do?act=showFile   
  321.               this.setSysMessage(request, "login.failAdmin", "btn.redownload",   
  322.                       "FileUpload.do?act=showFile");   
  323.               return mapping.findForward("error");   
  324.           }   
  325.   
  326.           return mapping.findForward("fileUpload");   
  327.       }   
  328.   
  329.       private boolean isValidFile(String fileName) {   
  330.           String[] validFiles = { "txt", "gif", "jpg", "jpeg", "jpe", "zip",   
  331.                   "rar", "doc", "ppt", "xls", "html", "htm", "tif", "tiff", "pdf" };   
  332.           boolean ret = false;   
  333.           for (int i = 0; i < validFiles.length; i++) {   
  334.               if (fileName.toLowerCase().endsWith(validFiles[i])) {   
  335.                   ret = true;   
  336.                   break;   
  337.               }   
  338.           }   
  339.           return ret;   
  340.       }   
  341.   
  342.       private String getContentType(String fileName) {   
  343.           String fileNameTmp = fileName.toLowerCase();   
  344.           String ret = "";   
  345.           if (fileNameTmp.endsWith("txt")) {   
  346.               ret = "text/plain";   
  347.           }   
  348.           if (fileNameTmp.endsWith("gif")) {   
  349.               ret = "image/gif";   
  350.           }   
  351.           if (fileNameTmp.endsWith("jpg")) {   
  352.               ret = "image/jpeg";   
  353.           }   
  354.           if (fileNameTmp.endsWith("jpeg")) {   
  355.               ret = "image/jpeg";   
  356.           }   
  357.           if (fileNameTmp.endsWith("jpe")) {   
  358.               ret = "image/jpeg";   
  359.           }   
  360.           if (fileNameTmp.endsWith("zip")) {   
  361.               ret = "application/zip";   
  362.           }   
  363.           if (fileNameTmp.endsWith("rar")) {   
  364.               ret = "application/rar";   
  365.           }   
  366.           if (fileNameTmp.endsWith("doc")) {   
  367.               ret = "application/msword";   
  368.           }   
  369.           if (fileNameTmp.endsWith("ppt")) {   
  370.               ret = "application/vnd.ms-powerpoint";   
  371.           }   
  372.           if (fileNameTmp.endsWith("xls")) {   
  373.               ret = "application/vnd.ms-excel";   
  374.           }   
  375.           if (fileNameTmp.endsWith("html")) {   
  376.               ret = "text/html";   
  377.           }   
  378.           if (fileNameTmp.endsWith("htm")) {   
  379.               ret = "text/html";   
  380.           }   
  381.           if (fileNameTmp.endsWith("tif")) {   
  382.               ret = "image/tiff";   
  383.           }   
  384.           if (fileNameTmp.endsWith("tiff")) {   
  385.               ret = "image/tiff";   
  386.           }   
  387.           if (fileNameTmp.endsWith("pdf")) {   
  388.               ret = "application/pdf";   
  389.           }   
  390.           return ret;   
  391.       }   
  392. }  

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值