struts 实现文件上传与下载

转载 2006年06月06日 17:24:00
struts 实现文件上传与下载

/*******************************************************************************
 * 文件名: FileUploadAction.java <br>
 * 版本: <br>
 * 描述: 一个文件上传,下载的Action,继承于BaseAcion <br>
 * 版权所有: <br>
 * //////////////////////////////////////////////////////// <br>
 * 创建者: 赵志强 <br>
 * 创建日期: 2005-10-28 <br>
 * 修改者: 赵志强 <br>
 * 修改日期: 2005-11-3 <br>
 * 修改说明: 添加gotoUpload方法,用户通过此方法跳转到upload.vm <br>
 ******************************************************************************/
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;
    }
}

相关文章推荐

struts2实现多文件上传和下载

  • 2015年04月23日 13:57
  • 14.44MB
  • 下载

struts2实现文件上传与下载功能

一、Demo介绍基于struts2框架,实现多文件的上传和下载功能。 实现原理图: 部分界面图: 上传成功及下载页面: 二、主要代码uploadFile.jsp:在form表单中包含一...

struts 实现文件上传与下载.rar

  • 2008年09月08日 15:31
  • 3KB
  • 下载

Struts2实现文件上传和下载

Struts2实现文件上传和下载 在做B/S系统时,通常会涉及到上传文件和下载文件,在没接struts2框架之前,我们都是使用apache下面的commons子项目的FileUplo...

用struts2实现的文件上传与下载

  • 2009年10月31日 19:38
  • 121KB
  • 下载

struts 实现文件上传与下载

package com.css.action; import java.io.FileInputStream; import java.io.InputStream; import java.io....

Struts实现文件上传与下载

第一步:编写页面文件 java" pageEncoding="UTF-8"%>       %@includefile="/header.jsp"%>     struts上传文件 ...

Struts2之实现文件上传与下载

在电脑前坐了一天,看看这个看看那个,也没什么意思,就翻一翻以前培训时的课件,整理整理全当做复习了。当我们用struts2进行文件上传时,首先要将from表单的enctype属性进行重新设置。那么该属性...
  • yxq08nt
  • yxq08nt
  • 2011年04月08日 23:08
  • 1155
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:struts 实现文件上传与下载
举报原因:
原因补充:

(最多只允许输入30个字)