1. 程式人生 > >struts2中實現檔案上傳功能

struts2中實現檔案上傳功能

package com.upload.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

import javax.servlet.ServletContext;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class UploadAction extends ActionSupport{

	private File upload;              //上傳檔案
	private String uploadFileName;    //上傳的檔名
	
	public File getUpload(){
	    return upload;
	}
	
	public void setUpload(File upload){
		this.upload = upload;
	}
	
	public String getUploadFileName(){
		return uploadFileName;
	}
	
	public void setUploadFileName(String uploadFileName){
		this.uploadFileName = uploadFileName;
	}
	
	
	
	public String upload() throws Exception{
		
		//如果選擇了上傳功能,則執行上傳操作;否則,不作任何操作
		if(getUpload() != null){	
			//根據上傳的檔案得到輸入流
			InputStream is = new FileInputStream(getUpload());
			//更改上傳檔名為:隨機數+上傳檔名		
			setUploadFileName(UUID.randomUUID().toString()+ getUploadFileName());
			//指定輸出流地址,此處是輸出到伺服器專案的根目錄下的images/userPhoto下
			OutputStream os = new FileOutputStream(getWebRootPath() + "images\\userPhoto\\" + getUploadFileName());
			
			byte buffer[] = new byte[1024];
			int count = 0;
			//把檔案寫到指定位置的檔案中
			while((count = is.read(buffer)) > 0){
				os.write(buffer, 0, count);
			}
			//關閉輸出流物件
			os.close();
			//關閉輸入流物件
			is.close();
			//返回
			return SUCCESS;
		}
		else {
			return ERROR;
		}
	}
		
	/**
	 * 獲得web專案根目錄
	 */
	public String getWebRootPath() throws Exception {
		ActionContext actionContext = ActionContext.getContext();
		ServletContext servletContext = (ServletContext)actionContext.get(ServletActionContext.SERVLET_CONTEXT);
		String rootPath = servletContext.getRealPath("/");
		return rootPath;
	}
}

upload.jsp