文件上传_struts2

 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 }

 

 

posted on 2014-11-03 19:18  @冰糖  阅读(114)  评论(0编辑  收藏  举报

导航