標籤:
檔案上傳
//準備檔案
1.上傳單個檔案頁面
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><%@ taglib prefix="s" uri="/struts-tags" %><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <base href="<%=basePath%>"> <title>檔案上傳</title> </head> <body> <!-- 上傳頁面的準備 --> <s:form action="upload.action" enctype="multipart/form-data" method="post"> <s:textfield name ="title" label ="標題"/><br/> <s:file name ="upload" label="選擇檔案"/><br/> <s:submit name ="submit" value ="上傳檔案"/> </s:form> </body></html>
2.在struts.xml中配置相應的action
<action name ="upload" class="action.UploadAction"> <!--通過param參數設定儲存目錄的路徑 --> <param name="savePath">/image</param> <result name="success">/upload_success.jsp</result> </action>
3.在根據action節點找對應的類
package action;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import org.apache.struts2.ServletActionContext;import com.opensymphony.xwork2.ActionSupport;public class UploadAction extends ActionSupport{ //封裝上傳檔案的屬性 private File upload; //封裝上傳檔案的類型 private String uploadContentType; //封裝上傳檔案的名稱 private String uploadFileName; public File getUpload() { return upload; } public void setUpload(File upload) { this.upload = upload; } public String getUploadContentType() { return uploadContentType; } public void setUploadContentType(String uploadContentType) { this.uploadContentType = uploadContentType; } public String getUploadFileName() { return uploadFileName; } public void setUploadFileName(String uploadFileName) { this.uploadFileName = uploadFileName; } public void setSavePath(String savePath) { this.savePath = savePath; } //擷取檔案上傳的路徑 private String savePath; @Override public String execute() throws Exception { //建立緩衝數組 byte [] buffer =new byte[1024]; //讀取檔案 FileInputStream fis =new FileInputStream(getUpload()); //儲存檔案,並設定儲存目錄的路徑 FileOutputStream fos =new FileOutputStream(getSavePath()+"\\"+this.getUploadFileName()); int length =fis.read(buffer); while(length>0){ //每次寫入length長度的內容 fos.write(buffer,0,length); length=fis.read(buffer); } fis.close(); fos.flush(); fos.close(); return SUCCESS; } public String getSavePath(){ return ServletActionContext.getServletContext().getRealPath(savePath); }}
4.如果成功就去找成功頁面
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><%@ taglib prefix="s" uri="/struts-tags" %><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <base href="<%=basePath%>"> <title>檔案上傳</title> </head> <body> <!--成功頁面 --> 上傳檔案成功! 您上傳的檔案是:<s:property value="uploadFileName"/><br/> 檔案類型:<s:property value="uploadContentType"/> </body></html>
單個檔案上傳