1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 4 <html> 5 <head> 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 7 <title>Insert title here</title> 8 </head> 9 <body> 10 <form action="upload" method="post" enctype="multipart/form-data"> 11 <input type="file" name="image"> 12 <input type="submit" value="上傳"> 13 14 </form> 15 16 17 <!-- <input type="file" name="upload"> 18 這個name對應後臺的 private File upload; 19 約定, 20 ,<s:file/>標誌不單單是綁定到upload,還有uploadContentType(上傳文件的MIME類型)和 uploadFileName(上傳文件的文件名,該文件名不包括文件的路徑)。
所以,<s:file name="xxx" />對應Action類裏面的xxx、xxxContentType和xxxFileName三個屬性。 --> 21 22 </body> 23 </html>
1 package com.helen.action; 2 3 import java.io.File; 4 5 import org.apache.commons.io.FileUtils; 6 import org.apache.struts2.ServletActionContext; 7 8 9 10 public class UploadAction { 11 private File image; //上傳的文件 12 private String imageFileName; //文件名稱 13 private String imageContentType; //文件類型 14 15 public String execute() throws Exception { 16 String realpath = ServletActionContext.getServletContext().getRealPath("/images"); 17 System.out.println("realpath: "+realpath); 18 if (image != null) { 19 File savefile = new File(new File(realpath), imageFileName); 20 if (!savefile.getParentFile().exists()) 21 savefile.getParentFile().mkdirs(); 22 FileUtils.copyFile(image, savefile); 23 } 24 25 26 return "success"; 27 } 28 29 public File getImage() { 30 return image; 31 } 32 33 public void setImage(File image) { 34 this.image = image; 35 } 36 37 public String getImageFileName() { 38 return imageFileName; 39 } 40 41 public void setImageFileName(String imageFileName) { 42 this.imageFileName = imageFileName; 43 } 44 45 public String getImageContentType() { 46 return imageContentType; 47 } 48 49 public void setImageContentType(String imageContentType) { 50 this.imageContentType = imageContentType; 51 } 52 53 54 55 }