Struts檔案上傳(FormFile)

來源:互聯網
上載者:User

標籤:port   pos   turn   並且   while   mapping   上傳   generated   eclips   

Struts中FormFile用於檔案進行上傳

1.在jsp檔案中進行定義

 

<form action="/StrutsFileUpAndDown/register.do" method="post" enctype="multipart/form-data">   名字:<input type="text" name="name" />   頭像:<input type="file" name="file"/>   <input type="submit" value="註冊使用者">   </form>

 

 

2.在Form表單中定義FormFile

/* * 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.ActionForm;import org.apache.struts.action.ActionMapping;import org.apache.struts.upload.FormFile;/**  * MyEclipse Struts * Creation date: 08-24-2017 *  * XDoclet definition: * @struts.form name="userForm" */public class UserForm extends ActionForm {/* * Generated Methods */private String username;private FormFile file;public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public FormFile getFile() {return file;}public void setFile(FormFile file) {this.file = file;}}

  

3.利用struts檔案進行關聯Form,關聯以後

1)利用表單一實例進行擷取FormFile執行個體,在擷取以後,我們可以通過FormFile擷取上傳檔案的各種資訊

UserForm userForm = (UserForm) form;String username = userForm.getUsername();FormFile file = userForm.getFile();//通過formFile可以擷取關於使用者上傳檔案的各種資訊//用於擷取檔案名稱字String fileName = file.getFileName();//用於擷取檔案大小int fileSize = file.getFileSize();

  

2)通過FormFile執行個體擷取輸入資料流,建立一個輸出資料流,並且在代碼中擷取tomcat伺服器的絕對路徑

try {//擷取輸入資料流is = file.getInputStream();//得到輸出資料流//1.得到file檔案夾,上傳到tomcat伺服器後的絕對路徑(file檔案為新建立的檔案夾) String filePath = this.getServlet().getServletContext().getRealPath("/file");//兩個"//"的其中一個"/"為轉義符 os=new FileOutputStream(filePath+"\\"+fileName); int len=0;//表示讀取的位元組//做一個緩衝,防止檔案過大而造成錯誤byte[] buff=new byte[1024];while((len=is.read(buff))!=-1){os.write(buff,0,len);}is.close();os.close(); }

  

 

Struts檔案上傳(FormFile)

相關文章

聯繫我們

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