struts 实现文件上传与下载

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;
    }
}

发布了2 篇原创文章 · 获赞 0 · 访问量 3万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章