標籤: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)