標籤:
第01步:配置web.xml
<?xml version="1.0" encoding="UTF-8"?><web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list></web-app>
第02步:編寫action類
package com.self.action;import java.io.File;import org.apache.commons.io.FileUtils;import org.apache.struts2.ServletActionContext;import com.opensymphony.xwork2.ActionContext;/**檔案上傳**/public class FileUpload { private File image;//得到上傳的檔案 private String imageFileName;//擷取上傳檔案的名稱,命名規則:頁面屬性名稱+FileName private String imageContentType;//得到上傳檔案的類型 public FileUpload() { } /**上傳方法**/ public String uploadFile(){ try { String realPath=ServletActionContext.getServletContext().getRealPath("/images"); System.out.println("工程路徑(/images路徑):"+realPath); if(image!=null){ System.out.println("已經獲得上傳檔案!"); File parentFile=new File(realPath);//指定檔案儲存路徑 if(!parentFile.exists()){//儲存路徑不存在,則建立 parentFile.mkdirs(); } File saveFile=new File(parentFile,imageFileName);//parentFile:儲存路徑,imageFileName:儲存檔案名稱 FileUtils.copyFile(image, saveFile);//將上傳的image複製到saveFile中 ActionContext.getContext().put("message", "儲存成功!"); } } catch (Exception e) { e.printStackTrace(); } return "tsuccess"; } public File getImage() { return image; } public void setImage(File image) { this.image = image; } public String getImageFileName() { return imageFileName; } public void setImageFileName(String imageFileName) { this.imageFileName = imageFileName; } public String getImageContentType() { return imageContentType; } public void setImageContentType(String imageContentType) { this.imageContentType = imageContentType; }}
第03步:配置struts.xml
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"><struts> <constant name="struts.action.extension" value="do,action"/> <package name="transform" namespace="/" extends="struts-default"> <action name="list_*" class="com.self.action.FileUpload" method="{1}"> <result name="tsuccess"> /outdata.jsp </result> </action> </package></struts>
第04步:編寫介面
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%><html> <body> <form method="post" action="list_uploadFile.action" enctype="multipart/form-data"> 檔案:<input type="file" name="image"> <BR> <input type="submit" value="上傳檔案"> </form> </body></html>
第05步:注意事項
儲存路徑:控制台輸出有,form表單方法:method="post",form表單類型:enctype="multipart/form-data",form表單input名字:同action裡面屬性名稱"image"
需要匯入包:
struts檔案上傳(單檔案)