【Struts2】文件上傳(一個文件和多個文件)

引言

         還記得學習struts1的時候做了文件上傳的Demo,現在學習Struts2了,同樣,再做一個文件上傳的Demo……

一、單個文件上傳

 步驟

        先將文件上傳相關的jar包引進來,分別是:commons-fileupload-1.2.1.jar和commons-io-1.3.2.jar

1、  建立上傳文件的index.jsp頁面

<span style="font-size:18px;"><%@ page language="java" contentType="text/html; charset=GB18030"  
    pageEncoding="GB18030"%>  
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
<html>  
<head>  
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">  
<title>Insert title here</title>  
</head>  
<body>  
    <form action="upload.action" method="post" enctype="multipart/form-data">  
        標題:<input type="text" name="title"><br>  
        文件:<input type="file" name="myFile"><br>  
        <input type="submit" value="上傳">  
    </form>  
</body>  
</html></span>  

2、  建立上傳成功的success.jsp頁面 


<span style="font-size:18px;"><%@ page language="java" contentType="text/html; charset=GB18030"  
    pageEncoding="GB18030"%>  
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
<html>  
<head>  
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">  
<title>Insert title here</title>  
</head>  
<body>  
    title:${title }<br>  
    fileName:${myFileFileName }<br>  
    myFileContentType:${myFileContentType }  
</body>  
</html></span>  

3、  建立UploadTestAction 


<span style="font-size:18px;">package com.bjpowernode.struts2;  
  
import java.io.BufferedInputStream;  
import java.io.BufferedOutputStream;  
import java.io.File;  
import java.io.FileInputStream;  
import java.io.FileOutputStream;  
import java.io.InputStream;  
import java.io.OutputStream;  
  
import com.opensymphony.xwork2.Action;  
  
public class UploadTestAction {  
    private String title;  
      
    public String getTitle() {  
        return title;  
    }  
  
    public void setTitle(String title) {  
        this.title = title;  
    }  
  
    //可以得到上傳文件的名稱  
    //規則:輸入域的名稱+固定字符串FileName  
    private String myFileFileName;  
      
    //取得文件數據  
    //規則:File 輸入域的名稱  
    private File myFile;  
      
    public File getMyFile() {  
        return myFile;  
    }  
  
    public void setMyFile(File myFile) {  
        this.myFile = myFile;  
    }  
  
    //取得內容類型  
    //規則:輸入域的名稱+固定字符串ContentType  
    private  String myFileContentType;  
      
    public String getMyFileFileName() {  
        return myFileFileName;  
    }  
  
    public void setMyFileFileName(String myFileFileName) {  
        this.myFileFileName = myFileFileName;  
    }  
  
    public String execute() throws Exception{  
        InputStream is= null;  
        OutputStream os = null;  
        try{  
            is = new BufferedInputStream(new FileInputStream(myFile));  
            os = new BufferedOutputStream(new FileOutputStream("c:\\" +  myFileFileName));  
            byte[] buffer = new byte[1024];  
            int len = 0;  
            while ((len = is.read(buffer)) >0 )  
            {  
                os.write(buffer,0,len);  
            }  
              
        }finally{  
            if(is != null) {is.close();}  
            if(os!=null){os.close();}  
        }  
        return Action.SUCCESS;  
    }  
}  
</span>  


4、  配置struts.xml配置文件 


<span style="font-size:18px;"><?xml version="1.0" encoding="UTF-8" ?>  
<!DOCTYPE struts PUBLIC  
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"  
    "http://struts.apache.org/dtds/struts-2.0.dtd">  
  
<struts>  
      
    <!-- 當struts.xml配置文件發生修改,會立刻加載,在生產環境下最好不要配置 -->  
     <constant name="struts.configuration.xml.reload" value="true"/>  
    <!-- 提供更友好的提示信息 -->  
    <constant name="struts.devMode" value="true"/>  
    <!-- 需要繼承struts-default包,這樣就擁有了最基本的功能 -->  
    <package name="upload-package" extends="struts-default">  
        <action name="upload" class="com.bjpowernode.struts2.UploadTestAction">  
            <result>/success.jsp</result>  
        </action>  
    </package>  
</struts>  
</span>  

問題

一、



         這個問題是因爲沒有配置臨時目錄導致的。下面我們配置一個臨時目錄。
         配置一個臨時目錄
         如果有struts2.properties文件可以設置:
<span style="font-size:18px;">       struts.multipart.saveDir =/tmp</span>  

        或者直接在struts.xml文件中配置:
<span style="font-size:18px;">      <constant name="struts.multipart.saveDir"value="/tmp"/></span>

        文件上傳是先將文件傳到我們指定的一個臨時目錄下,然後再通過IO操作將文件寫到我們真正要傳的目錄下。我們在Action中所定義的File類型的成員變量file實際上指向的就是臨時目錄中的臨時文件。

 二、



         出現了亂碼。

        我們需要在struts.xml配置文件中進行編碼的配置,這裏需要注意的是:同時要把jsp頁面的編碼進行修改,否則不起作用。

<span style="font-size:18px;"><!-- 防止亂碼    注意:同時還要把jsp中的編碼改成utf-8 -->  
    <constant name="struts.i18n.encoding" value="utf-8"/></span>  

二、多個文件上傳

         多個文件上傳與單個文件上傳相似,不過就是需要遍歷一下文件而已……

步驟

1、 建立上傳文件的fileupload2.jsp頁面

<span style="font-size:18px;"><%@ page language="java" contentType="text/html; charset=utf-8"  
    pageEncoding="GB18030"%>  
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
<html>  
<head>  
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">  
<title>Insert title here</title>  
</head>  
<body>  
<form action="upload2.action" method="post" enctype="multipart/form-data">  
        標題:<input type="text" name="title"><br>  
        文件1:<input type="file" name="file"><br>  
        文件2:<input type="file" name="file"><br>  
        文件3:<input type="file" name="file"><br>  
        <input type="submit" value="上傳">  
    </form>  
</body>  
</html></span>  

2、建立上傳成功的success2.jsp頁面

<span style="font-size:18px;"><%@ page language="java" contentType="text/html; charset=utf-8"  
    pageEncoding="GB18030"%>  
<%@ taglib prefix="s" uri="/struts-tags" %>  
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
<html>  
<head>  
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">  
<title>Insert title here</title>  
</head>  
<body>  
<!--     username:<s:property value="username"/><br> -->  
    <s:iterator value="fileFileName" id="f">  
    file:<s:property value="#f"/><br>  
    </s:iterator>  
</body>  
</html></span> 

3、建立UploadAction2

<span style="font-size:18px;">package com.bjpowernode.struts2;  
  
import java.io.File;  
import java.io.FileInputStream;  
import java.io.FileOutputStream;  
import java.io.InputStream;  
import java.io.OutputStream;  
import java.util.List;  
  
import org.apache.struts2.ServletActionContext;  
  
import com.opensymphony.xwork2.ActionSupport;  
  
public class UploadAction2 extends ActionSupport {  
    private String username;  
      
    private  List<File> file;  
      
    private List<String>fileFileName;  
      
    private List<String>fileContentType;  
      
    public String getUsername() {  
        return username;  
    }  
    public void setUsername(String username) {  
        this.username = username;  
    }  
    public List<File> getFile() {  
        return file;  
    }  
    public void setFile(List<File> file) {  
        this.file = file;  
    }  
    public List<String> getFileFileName() {  
        return fileFileName;  
    }  
    public void setFileFileName(List<String> fileFileName) {  
        this.fileFileName = fileFileName;  
    }  
    public List<String> getFileContentType() {  
        return fileContentType;  
    }  
    public void setFileContentType(List<String> fileContentType) {  
        this.fileContentType = fileContentType;  
    }  
      
    public String execute() throws Exception{  
        for(int i=0;i<file.size();i++)  
        {  
            InputStream is = new FileInputStream(file.get(i));  
            String root = ServletActionContext.getRequest().getRealPath("/upload");  
            File destFile = new File(root,fileFileName.get(i));  
            OutputStream os = new FileOutputStream(destFile);  
            byte[] buffer = new byte[400];  
            int length =0;  
            while(-1!=(length= is.read(buffer)))  
            {  
                os.write(buffer,0,length);  
            }  
            is.close();  
            os.close();       
            }  
        return  SUCCESS;  
    }  
}  
</span>  

4、配置struts.xml文件

<span style="font-size:18px;"><?xml version="1.0" encoding="UTF-8" ?>  
<!DOCTYPE struts PUBLIC  
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"  
    "http://struts.apache.org/dtds/struts-2.0.dtd">  
  
<struts>  
    <!-- 防止亂碼    注意:同時還要把jsp中的編碼改成utf-8 -->  
    <constant name="struts.i18n.encoding" value="utf-8"/>  
    <!-- 當struts.xml配置文件發生修改,會立刻加載,在生產環境下最好不要配置 -->  
     <constant name="struts.configuration.xml.reload" value="true"/>  
    <!-- 提供更友好的提示信息 -->  
    <constant name="struts.devMode" value="true"/>  
    <!-- 配置臨時目錄 -->  
    <constant name="struts.multipart.saveDir" value="/tmp"/>  
    <!--設置文件大小限制 ,也可以在struts.properties文件中進行配置,如果兩個都進行了配置,  
           那麼struts.properties的優先級高於struts.xml-->  
    <constant name="struts.multipart.maxSize" value="10485760"/>  
    <!-- 需要繼承struts-default包,這樣就擁有了最基本的功能 -->  
    <package name="upload-package" extends="struts-default">  
        <action name="upload" class="com.bjpowernode.struts2.UploadTestAction">  
            <result>/success.jsp</result>  
        </action>  
        <action name="upload2" class="com.bjpowernode.struts2.UploadAction2">  
            <result>/success2.jsp</result>  
              
            <interceptor-ref name="fileUpload">   
                <!--10485760=1024*1024*10 -->  
                <param name="maximumSize">10485760</param>  
            </interceptor-ref>   
            <interceptor-ref name="defaultStack"></interceptor-ref>  
        </action>  
    </package>  
</struts>  
</span>  

問題

一、


       
        這個問題是因爲我沒有在tomcat/webapps/struts_13目錄下面建立upload文件夾導致的。
       上傳成功了!


   
            換個大一點的文件試試

二、



       文件超過了限制,所以需要在配置文件中進行大小的限制。
       在struts.xml文件中配置:
<span style="font-size:18px;"><action name="upload2" class="com.bjpowernode.struts2.UploadAction2">  
            <result>/success2.jsp</result>  
              
            <interceptor-ref name="fileUpload">   
                <!--10485760=1024*1024*10(10M) -->  
                <param name="maximumSize">10485760</param>  
            </interceptor-ref>   
            <interceptor-ref name="defaultStack"></interceptor-ref>  
        </action></span>  
 
  注:當使用struts提供的文件上傳攔截器的時候,必須顯式的調用默認的攔截器棧。
          或者在struts.properties文件中配置:
<span style="font-size:18px;">struts.multipart.maxSize=10485760 </span>  

       以上就大功告成了!

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