struts 上傳檔案,struts

來源:互聯網
上載者:User

struts 上傳檔案,struts

檔案上傳的時候struts會使用預設18個攔截器中的<interceptor name="fileUpload" class="org.apache.struts2.interceptor.FileUploadInterceptor"/>進行處理。

檔案上傳Action類:

Action類中定義三個屬性:

private File file1; 對應表單:<input type="file" name="file1">
private String file1FileName; 檔案名稱
private String file1ContentType;檔案的類型(MIME)

並且提供這三個屬性的set方法。

檔案上傳表單:

<form action="${pageContext.request.contextPath }/fileUploadAction" method="post" enctype="multipart/form-data">  使用者名稱:<input type="text" name="userName"><br/>  檔案:<input type="file" name="file1"><br/>  <input type="submit" value="上傳">  </form>

檔案上傳使用的Action類UploadAction

package cn.itcast.upload;import java.io.File;import java.io.IOException;import org.apache.commons.io.FileUtils;import org.apache.struts2.ServletActionContext;import com.opensymphony.xwork2.ActionSupport;public class UploadAction extends ActionSupport{// 對應表單:<input type="file" name="file1">private File file1; // 檔案名稱private String file1FileName;// 檔案的類型(MIME)private String file1ContentType;public void setFile1(File file1) {this.file1 = file1;}public void setFile1FileName(String file1FileName) {this.file1FileName = file1FileName;}public void setFile1ContentType(String file1ContentType) {this.file1ContentType = file1ContentType;}public String upload() throws IOException{//得到上傳的檔案夾String path=ServletActionContext.getServletContext().getRealPath("/upload");//建立檔案File file=new File(path,file1FileName);//講上傳的檔案上傳到指定的檔案夾FileUtils.copyFile(file1, file);return "success";}}
struts.xml檔案的配置:

<struts><package name="upload_" extends="struts-default"><!-- 注意: action 的名稱不能用關鍵字"fileUpload" --><action name="fileUploadAction" class="cn.itcast.upload.UploadAction" method="upload"><result name="success">/index.jsp</result><!-- 配置錯誤視圖 --><result name="input">/error.jsp</result></action></package></struts>



著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.