Struts文件上傳(FormFile)


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(); 
		}

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM