strut2 單個檔案上傳

來源:互聯網
上載者:User

標籤:

  1. 第一步:在WEB-INF/lib下載入commons-fileupload-1.2.1.jar、commons-1.3.2.jar.這兩個檔案可從http://commons.apache.org/下載。
  2. 第二步:把from 表的enctype設定為:"multipart/form-data",如下:
    <from enctype="multipart/form-data" action="${pageContext.request.contextPath}/list.action" method="post"      <input type="file" name="uploadImage"></form>
  3. 第三步:在action類中添加以下代碼:
    package cn.itcast.action;import java.io.File;import org.apache.commons.io.FileUtils;import org.apache.struts2.ServletActionContext;import com.opensymphony.xwork2.ActionContext;public class HelloWorldAction {    private File image;    private String imageFileName;    public String getImageFileName() {        return imageFileName;    }    public void setImageFileName(String imageFileName) {        this.imageFileName = imageFileName;    }    public File getImage() {        return image;    }    public void setImage(File image) {        this.image = image;    }    public String addUI(){        return "success";    }    public String execute() throws Exception{                String realpath = ServletActionContext.getServletContext().getRealPath("/images");//得到檔案儲存的目錄(檔案的絕對路徑)        System.out.println(realpath);        if(image!=null){            File savefile = new File(new File(realpath), imageFileName);//savefile是一個完整的檔案路徑            if(!savefile.getParentFile().exists()) savefile.getParentFile().mkdirs();//如果儲存檔案的目錄不存在則建立目錄            FileUtils.copyFile(image, savefile);//調用系統函數拷貝檔案image到savefile中            ActionContext.getContext().put("message", "上傳成功");        }        return "success";    }}

    4.struts.xml檔案配置如下所示:

    <struts>    <constant name="struts.enable.DynamicMethodInvocation" value="false"/>    <!--控制檔案上傳的大小-->    <constant name="struts.multipart.maxSize" value="10701096"/>        <package name="employee" extends="struts-default">        <action name="list_*" class="cn.itcast.action.HelloWorldAction" method="{1}">            <result name="success">/WEB-INF/page/message.jsp</result>        </action>    </package></struts>

     

strut2 單個檔案上傳

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.