Struts2实现图片上传功能

项目整体目录结构

1、搭建Struts2框架

(1)导入Struts2相关jar包

(2)配置web.xml文件

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app version="2.5" 
 3     xmlns="http://java.sun.com/xml/ns/javaee" 
 4     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 5     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
 6     http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
 7     
 8     <filter>
 9         <filter-name>struts2</filter-name>
10         <filter-class>
11             org.apache.struts2.dispatcher.FilterDispatcher
12         </filter-class>
13     </filter>
14 
15     <filter-mapping>
16         <filter-name>struts2</filter-name>
17         <url-pattern>/*</url-pattern>
18     </filter-mapping>
19   <welcome-file-list>
20     <welcome-file>index.jsp</welcome-file>
21   </welcome-file-list>
22 </web-app>

(3)配置struts.xml文件

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE struts PUBLIC
 3     "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
 4     "http://struts.apache.org/dtds/struts-2.0.dtd">
 5 
 6 <struts>
 7 
 8     <constant name="struts.custom.i18n.resources" value="message" /> 
 9     
10     <constant name="struts.i18n.encoding" value="gbk"></constant>
11     
12     <!-- 上传过程中临时文件存放目录 -->
13     <constant name="struts.multipart.saveDir" value="c:\"></constant>
14     
15     <package name="struts2" extends="struts-default">
16     
17         <action name="upload"
18             class="com.broadengate.struts.UploadAction">
19             <result name="success">/uploadResult.jsp</result>
20             <result name="input">/index.jsp</result>
21             <!-- 定义文件上传拦截器 -->
22             <interceptor-ref name="fileUpload">
23                 <!-- 设置文件上传大小 -->
24                 <param name="maximumSize">409600</param>
25                 <!-- 设置文件上传类型 
26                 <param name="allowedTypes">
27                     application/vnd.ms-powerpoint
28                 </param>
29                 -->
30             </interceptor-ref>
31             <!-- 自定义了拦截器后必手动定义默认的拦截器,否则默认的拦截器不会被执行 -->
32             <interceptor-ref name="defaultStack"></interceptor-ref>
33         </action>
34         
35     </package>
36 
37 </struts>

2、index.jsp上传功能页面代码

要注意第6行,引入了struts2的tags的uri,否则tomcat不认识<s:...>标签

 1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
 2 <%
 3 String path = request.getContextPath();
 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 5 %>
 6 <%@ taglib prefix="s" uri="/struts-tags"%>
 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 8 <html>
 9   <head>
10     <base href="<%=basePath%>">
11     
12     <title>My JSP 'index.jsp' starting page</title>
13     <meta http-equiv="pragma" content="no-cache">
14     <meta http-equiv="cache-control" content="no-cache">
15     <meta http-equiv="expires" content="0">    
16     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
17     <meta http-equiv="description" content="This is my page">
18     <!--
19     <link rel="stylesheet" type="text/css" href="styles.css">
20     -->
21   </head>
22   
23   <body>
24 
25         <s:form action="upload" theme="simple" enctype="multipart/form-data">
26             <table align="center" width="50%" border="1">
27                 <tr>
28                     <td>username</td>
29                     <td><s:textfield name="username"></s:textfield></td>
30                 </tr>
31                 <tr>
32                     <td>password</td>
33                     <td><s:password name="password"></s:password></td>
34                 </tr>
35                 <tr>
36                     <td>file</td>
37                     <td id="more">
38                         <s:file name="file"></s:file>
39                         <input type="button" value="Add More.." onclick="addMore()">
40                     </td>
41                 </tr>
42                 <tr>
43                     <td><s:submit value=" submit "></s:submit></td>
44                     <td><s:reset value=" reset "></s:reset></td>
45                 </tr>
46             </table>
47         </s:form>
48   </body>
49 <script type="text/javascript">        
50 function addMore()
51 {
52     var td = document.getElementById("more");
53     
54     var br = document.createElement("br");
55     var input = document.createElement("input");
56     var button = document.createElement("input");
57     
58     input.type = "file";
59     input.name = "file";
60     
61     button.type = "button";
62     button.value = "Remove";
63     
64     button.onclick = function()
65     {
66         td.removeChild(br);
67         td.removeChild(input);
68         td.removeChild(button);
69     }
70     td.appendChild(br);
71     td.appendChild(input);
72     td.appendChild(button);
73 }
74 </script>
75 </html>

3、UploadAction.java,在struts.xml中配置的用于响应index.jsp页面中form的action属性的对应类

  1 package com.broadengate.struts;
  2 
  3 import java.io.File;
  4 import java.io.FileInputStream;
  5 import java.io.FileOutputStream;
  6 import java.io.InputStream;
  7 import java.io.OutputStream;
  8 import java.util.ArrayList;
  9 import java.util.List;
 10 
 11 import org.apache.struts2.ServletActionContext;
 12 
 13 import com.opensymphony.xwork2.ActionSupport;
 14 
 15 public class UploadAction extends ActionSupport {
 16     private String username;
 17 
 18     private String password;
 19 
 20     private List<File> file;
 21 
 22     private List<String> fileFileName;
 23 
 24     private List<String> fileContentType;
 25 
 26     private List<String> dataUrl;
 27     
 28 
 29     @Override
 30     public String execute() throws Exception {
 31         dataUrl = new ArrayList<String>();
 32         // �ļ����·��
 33         String imgpath = "upload/";
 34         for (int i = 0; i < file.size(); ++i) {
 35             InputStream is = new FileInputStream(file.get(i));
 36 
 37             String path = ServletActionContext.getServletContext().getRealPath("/");
 38             System.out.println(path);
 39         //    String root = "D:\\";
 40 
 41             dataUrl.add(imgpath+this.getFileFileName().get(i));
 42             File destFile = new File(path+imgpath, this.getFileFileName().get(i));
 43 
 44             OutputStream os = new FileOutputStream(destFile);
 45 
 46             byte[] buffer = new byte[400];
 47 
 48             int length = 0;
 49 
 50             while ((length = is.read(buffer)) > 0) {
 51                 os.write(buffer, 0, length);
 52             }
 53 
 54             is.close();
 55 
 56             os.close();
 57         }
 58         return SUCCESS;
 59     }
 60 
 61     
 62     
 63     
 64     public String getUsername() {
 65         return username;
 66     }
 67 
 68     public void setUsername(String username) {
 69         this.username = username;
 70     }
 71 
 72     public String getPassword() {
 73         return password;
 74     }
 75 
 76     public List<String> getDataUrl() {
 77         return dataUrl;
 78     }
 79 
 80 
 81 
 82 
 83     public void setDataUrl(List<String> dataUrl) {
 84         this.dataUrl = dataUrl;
 85     }
 86 
 87 
 88 
 89 
 90     public void setPassword(String password) {
 91         this.password = password;
 92     }
 93 
 94     public List<File> getFile() {
 95         return file;
 96     }
 97 
 98     public void setFile(List<File> file) {
 99         this.file = file;
100     }
101 
102     public List<String> getFileFileName() {
103         return fileFileName;
104     }
105 
106     public void setFileFileName(List<String> fileFileName) {
107         this.fileFileName = fileFileName;
108     }
109 
110     public List<String> getFileContentType() {
111         return fileContentType;
112     }
113 
114     public void setFileContentType(List<String> fileContentType) {
115         this.fileContentType = fileContentType;
116     }
117 }

4、显示上传结果页面uploadResult.jsp

 1 <%@ page language="java" contentType="text/html; charset=GB18030"
 2     pageEncoding="GB18030"%>
 3 <%
 4 String path = request.getContextPath();
 5 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 6 %>   
 7 <%@ taglib prefix="s" uri="/struts-tags" %>
 8  
 9 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
10 <html>
11 <head>
12 <base href="<%=basePath%>">
13 <meta http-equiv="Content-Type" content="text/html; charset=GB18030">
14 <title>Insert title here</title>
15 </head>
16 <body>
17 <%=basePath %>
18 username: <s:property value="username"/><br>
19 
20 password: <s:property value="password"/><br>
21 
22 file: <s:property value="fileFileName"/>
23 
24 
25 <s:iterator id="imgUrl" value="dataUrl">
26     <br /><img src="${imgUrl}"/>
27 </s:iterator>
28 </body>
29 </html>

5、我的Tomcat安装在D盘,要在“D:\Tomcat6.0\webapps\MyUpload”文件夹下新建一个upload文件夹,否则运行会报错,提示找不到路径,这个功能也可以在代码中添加。下边是运行效果:

(1)上传页面

(2)结果显示

ps:第一行的路径是写程序时做测试用的,没有实际意义。

posted @ 2013-03-05 10:42  ZH奶酪  阅读(32064)  评论(2编辑  收藏  举报