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

struts文件上传与下载简单DEMO

首先创建一个简单的project,配置其中的web.xml文件   applicationProject                       struts2              ...
  • xy18930914
  • xy18930914
  • 2016年03月30日 11:13
  • 1474

struts2 实现文件上传和下载

项目目录: web.xml:主要是配好struts2.
  • qiantujava
  • qiantujava
  • 2014年01月13日 17:29
  • 4168

七、Struts2之文件上传与下载

一、Struts2文件上传   Struts2的文件上传实现非常简单,只需要简单几步就可完成; 注意: (1)文件上传的struts2标签为: (2)文件上传的前提是表单属性method="...
  • xiazdong
  • xiazdong
  • 2012年02月03日 16:59
  • 24543

Spring整合Struts2实现多文件上传及下载

Sping与Struts环境的搭建在前文已经讲述过了,再次就不再做过多介绍了,详情请参考前文《Spring整合Struts2中拦截链与注解的使用 》。接下来进入正题,Struts2的多文件上传步骤。...
  • a1314517love
  • a1314517love
  • 2013年11月30日 20:20
  • 7266

struts 实现文件上传与下载

struts 实现文件上传与下载 /*******************...
  • basketwill
  • basketwill
  • 2007年05月05日 14:25
  • 506

struts 实现文件上传与下载

/******************************************************************************* * 文件名: FileUploadAc...
  • feigme
  • feigme
  • 2007年04月18日 19:13
  • 681

Struts实现文件上传与下载

第一步:编写页面文件 java" pageEncoding="UTF-8"%>       %@includefile="/header.jsp"%>     struts上传文件 ...
  • huahuahailang
  • huahuahailang
  • 2012年04月26日 07:14
  • 918

struts实现文件上传与下载

一.实现上传 二。实现下载
  • qq_33012203
  • qq_33012203
  • 2017年10月17日 00:59
  • 99

struts文件上传与下载

今天用struts编写了一个留言板测试程序,其中遇到了一些问题,有些我已经解决了,专门写篇博客记录一下,同时也希望路过的大牛能帮我指点一下我没解决的问题。 问题一:在表单中如果包含file控件,要在f...
  • Fan_He
  • Fan_He
  • 2016年11月29日 15:22
  • 146

使用Struts2框架进行文件的上传与下载

在struts2框架中,要遵循约定大于配置,下面是一个文件上传于下载的小例子,记下来以备忘 1.file数据库(用的数据库为mysql) 里面只有一张t_file表 id: int 主键 na...
  • huakaihualuo1223
  • huakaihualuo1223
  • 2012年09月20日 11:32
  • 2062
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:struts 实现文件上传与下载
举报原因:
原因补充:

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