找了一个 用Struts实现文件上传的代码,感觉不错,就收集了。

选择上传文件页面:selfile.jsp
--------------------------------------------------------------------------------
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html"%>
<html:html>
<html:form action="/uploadsAction.do" enctype="multipart/form-data">
<html:file property="theFile"/>
<html:submit/>
</html:form>
</html:html>
-------------------------------------------------------------------------------

UpLoadAction.java
--------------------------------------------------------------------------------
/*
 * Generated by MyEclipse Struts
 * Template path: templates/java/JavaClass.vtl
 */
package com.yourcompany.struts.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import java.io.*;
import javax.servlet.http.*;
import org.apache.struts.action.*;
import org.apache.struts.upload.FormFile;

import com.yourcompany.struts.form.*;

/**
 * MyEclipse Struts
 * Creation date: 12-07-2006
 *
 * XDoclet definition:
 * @struts.action validate="true"
 */
public class UpLoadAction extends Action {
 /*
  * Generated Methods
  */

 /**
  * Method execute
  * @param mapping
  * @param form
  * @param request
  * @param response
  * @return ActionForward
  */
 public ActionForward execute(ActionMapping mapping, ActionForm form,
   HttpServletRequest request, HttpServletResponse response) throws Exception{
  // if (form instanceof uploadsForm) {//如果form是uploadsForm
          String encoding = request.getCharacterEncoding();
          if ((encoding != null) && (encoding.equalsIgnoreCase("utf-8")))
          {
              response.setContentType("text/html; charset=gb2312");//如果没有指定编码,编码格式为gb2312
          }
          UpLoadForm theForm = (UpLoadForm ) form;
          FormFile file = theForm.getTheFile();//取得上传的文件
         
          String fileName = file.getFileName();//取得文件名
          int fileSize = file.getFileSize();//取得文件尺寸

          try {
           if(file==null)
           {
            return mapping.findForward("error3");
           }
           int fileMaxSize = 10 * 1024 * 1024;//文件最大限额
              if (fileSize > fileMaxSize) {
                  //文件大小不能超过fileMaxSize,如果超过,报"上传文件尺寸超过10M"错
                  return mapping.findForward("error1");
              }
             
              //测试该文件是不是合法
              if(!isValidFile(fileName))
              {    
                  return mapping.findForward("error2");
              }
             
          InputStream stream = file.getInputStream();//把文件读入
          String filePath = request.getRealPath("/");//取当前系统路径
          System.out.print(filePath);
          ByteArrayOutputStream baos = new ByteArrayOutputStream();
          OutputStream bos = new FileOutputStream(filePath + "/" +
                                                    file.getFileName());//建立一个上传文件的输出流
             //System.out.println(filePath+"/"+file.getFileName());
           
           
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ( (bytesRead = stream.read(buffer, 0, 8192)) != -1) {
              bos.write(buffer, 0, bytesRead);//将文件写入服务器
            }
            bos.close();
            stream.close();
           
          }catch(Exception e){
            System.err.print(e);
          }
          //request.setAttribute("dat",file.getFileName());
          return mapping.findForward("display");
     // }
    //  return null;
    }
  //判断文件类型是否合法!
  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;
    }
 }
--------------------------------------------------------------------------------

UpLoadForm.java
--------------------------------------------------------------------------------
/*
 * Generated by MyEclipse Struts
 * Template path: templates/java/JavaClass.vtl
 */
package com.yourcompany.struts.form;

import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;

import org.apache.struts.action.*;
import org.apache.struts.upload.*;


/**
 * MyEclipse Struts
 * Creation date: 12-07-2006
 *
 * XDoclet definition:
 * @struts.form name="upLoadForm"
 */
public class UpLoadForm extends ActionForm {
 /*
  * Generated Methods
  */

 /**
  * Method validate
  * @param mapping
  * @param request
  * @return ActionErrors
  */
 
  public static final String ERROR_PROPERTY_MAX_LENGTH_EXCEEDED = "org.apache.struts.webapp.upload.MaxLengthExceeded";
   protected FormFile theFile;
  
   public FormFile getTheFile() {
       return theFile;
   }
   public void setTheFile(FormFile theFile) {
       this.theFile = theFile;
   }

 public ActionErrors validate(ActionMapping mapping,
   HttpServletRequest request) {
  ActionErrors errors = null;
       //has the maximum length been exceeded?
       Boolean maxLengthExceeded = (Boolean)
               request.getAttribute(MultipartRequestHandler.ATTRIBUTE_MAX_LENGTH_EXCEEDED);
       if ((maxLengthExceeded != null) && (maxLengthExceeded.booleanValue()))
       {
           errors = new ActionErrors();
           errors.add(ERROR_PROPERTY_MAX_LENGTH_EXCEEDED, new ActionError("maxLengthExceeded"));
       }
       return errors;

   }

 /**
  * Method reset
  * @param mapping
  * @param request
  */
 public void reset(ActionMapping mapping, HttpServletRequest request) {
  // TODO Auto-generated method stub
 }
}

--------------------------------------------------------------------------------

struts-config.xml
--------------------------------------------------------------------------------
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">
<struts-config>
  <form-beans>
    <form-bean name="uploadsForm" type="UpLoadForm" />
  </form-beans>
  <action-mappings>
    <action name="uploadsForm" type="UpLoadAction" path="/uploadsAction">
       <forward name="display" path="/success.jsp" />
      <forward name="error1" path="/error1.jsp" />
      <forward name="error2" path="/error2.jsp" />
      <forward name="error3" path="/error3.jsp" />
    </action>
  </action-mappings>
</struts-config>
<!--success.jsp就是随便写一个成功页-->

posted on 2006-12-07 18:57  zxynet(海洋之星)  阅读(392)  评论(0)    收藏  举报