struts2 文件上传

一.简介

Struts2并未提供自己的请求解析器,也就是就Struts2不会自己去处理multipart/form-data的请求,它需要调用其他请求解析器,将HTTP请求中的表单域解析出来。但Struts2在原有的上传解析器基础上做了进一步封装,更进一步简化了文件上传。
Struts2默认使用的是Jakarta的Common-FileUpload框架来上传文件,因此,要在web应用中增加两个Jar文件:commons-fileupload-1.2.jar和commons-io-1.3.1.jar。它在原上传框架上做了进一步封装,简化了文件上传的代码实现,取消了不同上传框架上的编程差异。
如果要改成其它的文件上传框架,可以修改struts.multipart.parser常量的值为cos/pell,默认值是jakata。并在classpath中增加相应上传组件的类库

例如配置成cos上传

struts.multipart.parser=cos

struts.multipart.maxSize=1024  指定文件的最大字结数

 

二.原理

不管用common-fileUPload框架,还是用cos,都是通过将HTTP的数据保存到临时文件夹,然后Struts使用fileUpload拦截器将文件绑定到Action的实例中。

 

 

三.需要的jar包(默认使用commons-fileupload,如果使用cos,要将jar引进来)

commons-logging-1.1.jar
freemarker-2.3.8.jar
ognl-2.6.11.jar
struts2-core-2.0.6.jar
xwork-2.0.1.jar
commons-io-1.3.1.jar
commons-fileupload-1.2.jar

 

四.实例

1.首先,创建上传页面

Html代码 复制代码
  1. <%@page language="java" contentType = "text/html; charset=utf-8" pageEncoding = "utf-8"%>    
  2. <%@taglib prefix="s" uri ="/struts-tags"%>    
  3.   
  4.   
  5. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  6. <html>  
  7.   <head>  
  8.   
  9.     <title>My JSP 'FileUpload.jsp' starting page</title>  
  10.        
  11.     <meta http-equiv="pragma" content="no-cache">  
  12.     <meta http-equiv="cache-control" content="no-cache">  
  13.     <meta http-equiv="expires" content="0">       
  14.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  15.     <meta http-equiv="description" content="This is my page">  
  16.     <!--  
  17.     <link rel="stylesheet" type="text/css" href="styles.css">  
  18.     -->  
  19.   
  20.   </head>  
  21.      
  22.   <body>  
  23.    <s:form action ="fileUpload" method ="POST" enctype ="multipart/form-data">    
  24.         <s:fielderror />  
  25.         <s:file name ="upload"/>      
  26.         <s:submit />    
  27.     </s:form >    
  28.   
  29.   </body>  
  30. </html>  
<%@page language="java" contentType = "text/html; charset=utf-8" pageEncoding = "utf-8"%> 
<%@taglib prefix="s" uri ="/struts-tags"%> 


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>

    <title>My JSP 'FileUpload.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  
  <body>
   <s:form action ="fileUpload" method ="POST" enctype ="multipart/form-data"> 
		<s:fielderror />
        <s:file name ="upload"/>   
        <s:submit /> 
    </s:form > 

  </body>
</html>

 

 

2.action

Java代码 复制代码
  1. package com;   
  2.   
  3. import java.io.BufferedInputStream;   
  4. import java.io.BufferedOutputStream;   
  5. import java.io.File;   
  6. import java.io.FileInputStream;   
  7. import java.io.FileOutputStream;   
  8. import java.io.InputStream;   
  9. import java.io.OutputStream;   
  10. import java.util.Date;   
  11.   
  12. import org.apache.struts2.ServletActionContext;   
  13.   
  14. import com.opensymphony.xwork2.ActionSupport;   
  15.   
  16. public class FileUploadAction extends ActionSupport {   
  17.        
  18.     private static final long serialVersionUID = 572146812454l;   
  19.   
  20.     private File upload;   
  21.   
  22.     private String uploadContentType;   
  23.   
  24.     private String uploadFileName;   
  25.   
  26.     private String imageFileName;   
  27.   
  28.     public String getUploadContentType() {   
  29.         return uploadContentType;   
  30.     }   
  31.   
  32.     public void setUploadContentType(String uploadContentType) {   
  33.         this.uploadContentType = uploadContentType;   
  34.     }   
  35.   
  36.     public File getUpload() {   
  37.         return upload;   
  38.     }   
  39.   
  40.     public void setUpload(File upload) {   
  41.         this.upload = upload;   
  42.     }   
  43.   
  44.     public String getUploadFileName() {   
  45.         return uploadFileName;   
  46.     }   
  47.   
  48.     public void setUploadFileName(String uploadFileName) {   
  49.         this.uploadFileName = uploadFileName;   
  50.     }   
  51.   
  52.     public void setImageFileName(String imageFileName) {   
  53.         this.imageFileName = imageFileName;   
  54.     }   
  55.   
  56.     public String getImageFileName() {   
  57.         return imageFileName;   
  58.     }   
  59.   
  60.     private static void copy(File src, File dst) {   
  61.         try {   
  62.             InputStream in = null;   
  63.             OutputStream out = null;   
  64.             try {   
  65.                 in = new BufferedInputStream(new FileInputStream(src));   
  66.                 out = new BufferedOutputStream(new FileOutputStream(dst));   
  67.                 byte[] buffer = new byte[1024*10];   
  68.                 while (in.read(buffer) > 0) {   
  69.                     out.write(buffer);   
  70.                 }   
  71.             } finally {   
  72.                 if (null != in) {   
  73.                     in.close();   
  74.                 }   
  75.                 if (null != out) {   
  76.                     out.close();   
  77.                 }   
  78.             }   
  79.         } catch (Exception e) {   
  80.             e.printStackTrace();   
  81.         }   
  82.     }   
  83.   
  84.     @Override  
  85.     public String execute() {   
  86.         System.out.println(uploadFileName);   
  87.            
  88.         imageFileName = System.currentTimeMillis() + uploadFileName.substring(uploadFileName.lastIndexOf("."));   
  89.         File imageFile = new File(ServletActionContext.getServletContext()   
  90.                 .getRealPath("/uploadImages")   
  91.                 + "/" + imageFileName);   
  92.         copy(upload, imageFile);   
  93.         return SUCCESS;   
  94.     }   
  95.   
  96. }  
package com;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class FileUploadAction extends ActionSupport {
	
	private static final long serialVersionUID = 572146812454l;

	private File upload;

	private String uploadContentType;

	private String uploadFileName;

	private String imageFileName;

	public String getUploadContentType() {
		return uploadContentType;
	}

	public void setUploadContentType(String uploadContentType) {
		this.uploadContentType = uploadContentType;
	}

	public File getUpload() {
		return upload;
	}

	public void setUpload(File upload) {
		this.upload = upload;
	}

	public String getUploadFileName() {
		return uploadFileName;
	}

	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	public void setImageFileName(String imageFileName) {
		this.imageFileName = imageFileName;
	}

	public String getImageFileName() {
		return imageFileName;
	}

	private static void copy(File src, File dst) {
		try {
			InputStream in = null;
			OutputStream out = null;
			try {
				in = new BufferedInputStream(new FileInputStream(src));
				out = new BufferedOutputStream(new FileOutputStream(dst));
				byte[] buffer = new byte[1024*10];
				while (in.read(buffer) > 0) {
					out.write(buffer);
				}
			} finally {
				if (null != in) {
					in.close();
				}
				if (null != out) {
					out.close();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public String execute() {
		System.out.println(uploadFileName);
		
		imageFileName = System.currentTimeMillis() + uploadFileName.substring(uploadFileName.lastIndexOf("."));
		File imageFile = new File(ServletActionContext.getServletContext()
				.getRealPath("/uploadImages")
				+ "/" + imageFileName);
		copy(upload, imageFile);
		return SUCCESS;
	}

}

 

 

表单的enctype ="multipart/form-data,与一般的上传一样.

<s:file name="upload">会将upload绑定到action的upload,其次他还会将上传记文件的MIME类型绑定到uploadContentType,文件名绑定到uploadFileName中,他们是通过setUploadContentType和setUploadFileName进行绑定的

 

3.struts.xml的配置

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.     <constant name="struts.multipart.saveDir" value="/tmp" />  
  8.     <package name="fileUploadDemo" extends="struts-default">  
  9.         <action name ="fileUpload" class ="com.FileUploadAction">    
  10.             <!-- 验证上传文件的类型 -->  
  11.             <interceptor-ref name ="fileUpload">    
  12.                 <param name ="allowedTypes">image/bmp,image/png,image/gif,image/jpeg,image/jpg</param>    
  13.             </interceptor-ref>    
  14.             <interceptor-ref name ="defaultStack"/>    
  15.             <!-- 如果加入了验证上传文件的类型,必须要加input -->  
  16.             <result name ="input" >/fileUpload.jsp</result>  
  17.             <result name ="success">/showUpload.jsp </result>    
  18.         </action>    
  19.     </package>  
  20. </struts>  

 

 

4.最后是web.xml的配置

Xml代码 复制代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app version="2.4"    
  3.     xmlns="http://java.sun.com/xml/ns/j2ee"    
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    
  5.     xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee    
  6.     http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">  
  7.        
  8.     <filter>    
  9.         <filter-name>struts-cleanup</filter-name>    
  10.         <filter-class>    
  11.             org.apache.struts2.dispatcher.ActionContextCleanUp   
  12.         </filter-class>    
  13.     </filter>    
  14.        
  15.     <filter>    
  16.         <filter-name>struts2</filter-name >    
  17.         <filter-class>    
  18.             org.apache.struts2.dispatcher.FilterDispatcher   
  19.         </filter-class >    
  20.     </filter>    
  21.        
  22.     <filter-mapping>    
  23.         <filter-name>struts-cleanup</filter-name >    
  24.         <url-pattern>/*</url-pattern>    
  25.     </filter-mapping>    
  26.   
  27.     <filter-mapping>    
  28.         <filter-name>struts2</filter-name >    
  29.         <url-pattern>/*</url-pattern >    
  30.     </filter-mapping>    
  31.        
  32.   <welcome-file-list>  
  33.     <welcome-file>index.jsp</welcome-file>  
  34.   </welcome-file-list>  
  35. </web-app>  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值