struts1.x上傳文件大小設置

一、web.xml配置,這裏將文件上傳配置爲upload模塊。

<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE web-app
  PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
  "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">
<web-app>
 <display-name>Struts Blank Application</display-name>
  
  <!-- Standard Action Servlet Configuration (with debugging) -->
  <servlet>
    <servlet-name>action</servlet-name>
    <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
    <init-param>
      <param-name>config</param-name>
      <param-value>/WEB-INF/struts-config.xml</param-value>
    </init-param>
    <init-param>
      <param-name>config/upload</param-name>
      <param-value>/WEB-INF/upload/struts-config.xml</param-value>
    </init-param>

<init-param>
      <param-name>debug</param-name>
      <param-value>2</param-value>
    </init-param>
    <init-param>
      <param-name>detail</param-name>
      <param-value>2</param-value>
    </init-param>
    <load-on-startup>2</load-on-startup>
  </servlet>


  <!-- Standard Action Servlet Mapping -->
  <servlet-mapping>
    <servlet-name>action</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>


  <!-- The Usual Welcome File List -->
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>


  <!-- Struts Tag Library Descriptors -->
  <taglib>
    <taglib-uri>/tags/struts-bean</taglib-uri>
    <taglib-location>/WEB-INF/struts-bean.tld</taglib-location>
  </taglib>

  <taglib>
    <taglib-uri>/tags/struts-html</taglib-uri>
    <taglib-location>/WEB-INF/struts-html.tld</taglib-location>
  </taglib>

  <taglib>
    <taglib-uri>/tags/struts-logic</taglib-uri>
    <taglib-location>/WEB-INF/struts-logic.tld</taglib-location>
  </taglib>

  <taglib>
    <taglib-uri>/tags/struts-nested</taglib-uri>
    <taglib-location>/WEB-INF/struts-nested.tld</taglib-location>
  </taglib>

  <taglib>
    <taglib-uri>/tags/struts-tiles</taglib-uri>
    <taglib-location>/WEB-INF/struts-tiles.tld</taglib-location>
  </taglib>

</web-app>

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

二、struts-config.xml配置和資源文件

--------------------------------------------------------------------------------
<?xml version="1.0" encoding="iso-8859-1"?>

<!DOCTYPE struts-config PUBLIC
          "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN"
          "http://struts.apache.org/dtds/struts-config_1_2.dtd">
<struts-config>
  <form-beans>
    <form-bean name="uploadForm" type="org.apache.struts.webapp.upload.UpLoadForm" />
  </form-beans>
  <action-mappings>
    <action path="/upload" forward="/selfile.jsp" />
    <!-- Upload Action -->
    <action path="/uploadsAction" 
            type="org.apache.struts.webapp.upload.UpLoadAction"   
            name="uploadForm" scope="request" input="input">
      <forward name="input" path="/selfile.jsp" />
      <forward name="display" path="/display.jsp" />
    </action>
  </action-mappings>
  <!-- 這裏設置上傳文件的最大值。 -1 不限制大小。缺省值:-1 -->
  <controller maxFileSize="2M" inputForward="true" />
  <message-resources parameter="org.apache.struts.webapp.upload.UploadResources"/>

</struts-config>

  資源文件:UploadResources_zh_CN.properties
maxLengthExceeded=已經超過了上傳文件所允許的最大值。
maxLengthExplanation=注意:這個應用程序允許上傳文件的最大值是2M。請看"/WEB-INF/upload/struts-config.xml" 文件更改這個值。

三、選擇上傳文件頁面:selfile.jsp,如此訪問此頁面:
<html:link module="/upload" page="/upload.do"> 繼續上傳</html:link></h2>

--------------------------------------------------------------------------------
<%@ page contentType="text/html; charset=GBK" %>
<%@ page import="org.apache.struts.action.*,
                 java.util.Iterator,
                 org.apache.struts.Globals" %>
<%@ taglib uri="/tags/struts-bean" prefix="bean" %>
<%@ taglib uri="/tags/struts-html" prefix="html" %>
<%@ taglib uri="/tags/struts-logic" prefix="logic" %>
<logic:messagesPresent>
   <ul>
   <html:messages id="error">
      <li><bean:write name="error"/></li>
   </html:messages>
   </ul><hr />
</logic:messagesPresent>
<html:html>

<html:form action="uploadsAction.do" enctype="multipart/form-data">
<html:file property="theFile"/>
<html:submit/>
</html:form>
</html:html>

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

四、表單bean:  UpLoadForm.java

--------------------------------------------------------------------------------
package org.apache.struts.webapp.upload;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.*;
import org.apache.struts.upload.*;

/**
 * <p>Title:UpLoadForm</p>
 * <p>Description: QRRSMMS </p>
 * <p>Copyright: Copyright (c) 2004 jiahansoft</p>
 * <p>Company: jiahansoft</p>
 * @author wanghw
 * @version 1.0
 */

public class UpLoadForm extends ActionForm {
  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(
                ActionMessages.GLOBAL_MESSAGE ,
                new ActionMessage("maxLengthExceeded"));
            errors.add(
                ActionMessages.GLOBAL_MESSAGE ,
                new ActionMessage("maxLengthExplanation"));
        }
        return errors;

    }

}


--------------------------------------------------------------------------------
五、處理上傳的文件:UpLoadAction.java 
--------------------------------------------------------------------------------
package org.apache.struts.webapp.upload;
import java.io.*;
import javax.servlet.http.*;
import org.apache.struts.action.*;
import org.apache.struts.upload.FormFile; 

/**
 * <p>Title:UpLoadAction</p>
 * <p>Description: QRRSMMS </p>
 * <p>Copyright: Copyright (c) 2004 jiahansoft</p>
 * <p>Company: jiahansoft</p>
 * @author wanghw
 * @version 1.0
 */

public class UpLoadAction extends Action {
  public ActionForward execute(ActionMapping mapping,
                               ActionForm form,
                               HttpServletRequest request,
                               HttpServletResponse response)
      throws Exception {
       if (form instanceof UpLoadForm) {//如果form是UpLoadsForm
           String encoding = request.getCharacterEncoding();

       if ((encoding != null) && (encoding.equalsIgnoreCase("utf-8")))
        {
            response.setContentType("text/html; charset=gb2312");
        }
        UpLoadForm theForm = (UpLoadForm ) form;
        FormFile file = theForm.getTheFile();//取得上傳的文件
        String contentType = file.getContentType();

        String size = (file.getFileSize() + " bytes");//文件大小
        String fileName= file.getFileName();//文件名
        try {
          InputStream stream = file.getInputStream();//把文件讀入
          String filePath = request.getRealPath("/");//取當前系統路徑
          ByteArrayOutputStream baos = new ByteArrayOutputStream();
          OutputStream bos = new FileOutputStream(filePath + "/" +
                                                  file.getFileName());
              //建立一個上傳文件的輸出流,將上傳文件存入web應用的根目錄。
          //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());
         request.setAttribute("contentType", contentType);
         request.setAttribute("size", size);
         request.setAttribute("fileName", fileName);

        return mapping.findForward("display");
    }
    return null;
  }
}
------------------------------------------------------------------------------------------

五、成功頁display.jsp 
<%@ page contentType="text/html; charset=GBK" %>
<%@ page import="org.apache.struts.action.*,
                 java.util.Iterator,
                 org.apache.struts.Globals" %>
<%@ taglib uri="/tags/struts-html" prefix="html" %>


上傳成功!上傳信息如下:
<p>
<b>The File name:</b> <%= request.getAttribute("fileName") %>
</p>
<p>
<b>The File content type:</b> <%= request.getAttribute("contentType") %>
</p>
<p>
<b>The File size:</b> <%= request.getAttribute("size") %>
</p>
<hr />
<hr />
<html:link module="/upload" page="/upload.do"> 繼續上傳</html:link></h2>
 六、測試
 從本站下載整個目錄結構TestStruts並放入tomcat的webapps目錄下,在瀏覽器中輸入:
http://127.0.0.1:8080/TestStruts/upload/upload.do

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章