`

struts2详解(二)---->>单个文件上传

阅读更多

实现原理:
      Struts 2是通过Commons FileUpload文件上传。Commons FileUpload通过将HTTP的数据保存到临时文件夹,然后Struts使用fileUpload拦截器将文件绑定到Action的实例中。从而我们就能够以本地文件方式的操作浏览器上传的文件。

具体实现
    先要引入必要的jar包:

 

1、首先,创建文件上传页面index.jsp,内容如下:

Jsp代码 复制代码 收藏代码
  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>   
  2. <%   
  3.     String path = request.getContextPath();   
  4.     String basePath = request.getScheme() + "://"  
  5.             + request.getServerName() + ":" + request.getServerPort()   
  6.             + path + "/";   
  7. %>   
  8.   
  9. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">   
  10. <html>   
  11.     <head>   
  12.         <base href="<%=basePath%>">   
  13.   
  14.         <title>My JSP 'index.jsp' starting page</title>   
  15.         <meta http-equiv="pragma" content="no-cache">   
  16.         <meta http-equiv="cache-control" content="no-cache">   
  17.         <meta http-equiv="expires" content="0">   
  18.         <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">   
  19.         <meta http-equiv="description" content="This is my page">   
  20.         <!--   
  21.     <link rel="stylesheet" type="text/css" href="styles.css">   
  22.     -->   
  23.     </head>   
  24.     <body>   
  25.         <div align="center">   
  26.             <!-- enctype="multipart/form-data" 这个属性是必须得有的 -->   
  27.             <form action="csdn/upload.action" method="post"  
  28.                 enctype="multipart/form-data">   
  29.                 <table border="1px">   
  30.                     <tr>   
  31.                         <td>   
  32.                             标题:   
  33.                         </td>   
  34.                         <td>   
  35.                             <input type="text" name="title" />   
  36.                         </td>   
  37.                     </tr>   
  38.                     <tr>   
  39.                         <td>   
  40.                             文件:   
  41.                         </td>   
  42.                         <td>   
  43.                             <input type="file" name="pic" />   
  44.                         </td>   
  45.                     </tr>   
  46.                     <tr>   
  47.                         <td colspan="2" align="center">   
  48.                             <input type="submit" value="上传" />   
  49.                         </td>   
  50.                     </tr>   
  51.                 </table>   
  52.             </form>   
  53.   
  54.         </div>   
  55.     </body>   
  56. </html>  
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
	<head>
		<base href="<%=basePath%>">

		<title>My JSP 'index.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>
		<div align="center">
			<!-- enctype="multipart/form-data" 这个属性是必须得有的 -->
			<form action="csdn/upload.action" method="post"
				enctype="multipart/form-data">
				<table border="1px">
					<tr>
						<td>
							标题:
						</td>
						<td>
							<input type="text" name="title" />
						</td>
					</tr>
					<tr>
						<td>
							文件:
						</td>
						<td>
							<input type="file" name="pic" />
						</td>
					</tr>
					<tr>
						<td colspan="2" align="center">
							<input type="submit" value="上传" />
						</td>
					</tr>
				</table>
			</form>

		</div>
	</body>
</html>

 

 

备注:
    在index.jsp中,先将表单的提交方式设为POST,然后将enctype设为multipart/form-data

 

2、其次是UserAction.java代码

Java代码 复制代码 收藏代码
  1. package cn.csdn.struts2.action;   
  2.   
  3. import java.io.File;   
  4. import java.io.IOException;   
  5.   
  6. import org.apache.commons.io.FileUtils;   
  7. import org.apache.struts2.ServletActionContext;   
  8.   
  9. import com.opensymphony.xwork2.ActionSupport;   
  10.   
  11. public class UserAction extends ActionSupport{   
  12.   
  13.     /**  
  14.      * @author z_xiaofei168  
  15.      */  
  16.     private static final long serialVersionUID = 1L;   
  17.        
  18.     /** 标题 */  
  19.     private String title;   
  20.     /** 获取文件   文件名与视图层的名称一致 */  
  21.     private File pic;   
  22.     /** 获取文件的类型     必须是:  文件名+ContentType */  
  23.     private String picContentType;   
  24.     /** 获取文件的名称     必须是:   文件名+FileName  */  
  25.     private String picFileName;   
  26.     /** 保存文件路径      /保存文件的文件名称  */  
  27.     private String savePath;   
  28.        
  29.     public String getTitle() {   
  30.         return title;   
  31.     }   
  32.     public void setTitle(String title) {   
  33.         this.title = title;   
  34.     }   
  35.     public File getPic() {   
  36.         return pic;   
  37.     }   
  38.     public void setPic(File pic) {   
  39.         this.pic = pic;   
  40.     }   
  41.     public String getPicContentType() {   
  42.         return picContentType;   
  43.     }   
  44.     public void setPicContentType(String picContentType) {   
  45.         this.picContentType = picContentType;   
  46.     }   
  47.     public String getPicFileName() {   
  48.         return picFileName;   
  49.     }   
  50.     public void setPicFileName(String picFileName) {   
  51.         this.picFileName = picFileName;   
  52.     }   
  53.     public String getSavePath() {   
  54.         /**获取上下的路径*/  
  55.         return ServletActionContext.getServletContext().getRealPath(savePath);   
  56.     }   
  57.     public void setSavePath(String savePath) {   
  58.         this.savePath = savePath;   
  59.     }   
  60.        
  61.        
  62.     /** copy读取  */  
  63.     public String uploadFile(){   
  64.         System.out.println("savePath:"+savePath);   
  65.         System.out.println("pic:"+pic);   
  66.         System.out.println("picContentType:"+picContentType);   
  67.         System.out.println("picFileName:"+picFileName);   
  68.         System.out.println("getSavePath():"+getSavePath());   
  69.         /**保存的具体路径*/  
  70.         String savepath = getSavePath();   
  71.         /**根据保存的路径创建file对象*/  
  72.         File file = new File(savepath);   
  73.         if(!file.exists()){   
  74.             /**创建此文件对象路径*/  
  75.             file.mkdirs();   
  76.         }   
  77.         try {   
  78.             /**使用的是:org.apache.commons.io.FileUtils FileUtils*/  
  79.             FileUtils.copyFile(pic, new File(file,getPicFileName()));   
  80.         } catch (IOException e) {   
  81.             e.printStackTrace();   
  82.         }   
  83.         return SUCCESS;   
  84.     }   
  85. }  
package cn.csdn.struts2.action;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class UserAction extends ActionSupport{

	/**
	 * @author z_xiaofei168
	 */
	private static final long serialVersionUID = 1L;
	
	/** 标题 */
	private String title;
	/** 获取文件   文件名与视图层的名称一致 */
	private File pic;
	/** 获取文件的类型     必须是:  文件名+ContentType */
	private String picContentType;
	/** 获取文件的名称     必须是:   文件名+FileName  */
	private String picFileName;
	/** 保存文件路径      /保存文件的文件名称  */
	private String savePath;
	
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public File getPic() {
		return pic;
	}
	public void setPic(File pic) {
		this.pic = pic;
	}
	public String getPicContentType() {
		return picContentType;
	}
	public void setPicContentType(String picContentType) {
		this.picContentType = picContentType;
	}
	public String getPicFileName() {
		return picFileName;
	}
	public void setPicFileName(String picFileName) {
		this.picFileName = picFileName;
	}
	public String getSavePath() {
		/**获取上下的路径*/
		return ServletActionContext.getServletContext().getRealPath(savePath);
	}
	public void setSavePath(String savePath) {
		this.savePath = savePath;
	}
	
	
	/** copy读取  */
	public String uploadFile(){
		System.out.println("savePath:"+savePath);
		System.out.println("pic:"+pic);
		System.out.println("picContentType:"+picContentType);
		System.out.println("picFileName:"+picFileName);
		System.out.println("getSavePath():"+getSavePath());
		/**保存的具体路径*/
		String savepath = getSavePath();
		/**根据保存的路径创建file对象*/
		File file = new File(savepath);
		if(!file.exists()){
			/**创建此文件对象路径*/
			file.mkdirs();
		}
		try {
			/**使用的是:org.apache.commons.io.FileUtils FileUtils*/
			FileUtils.copyFile(pic, new File(file,getPicFileName()));
		} catch (IOException e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}
}

  

3、配置文件: struts.xml

Xml代码 复制代码 收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2.  <!DOCTYPE struts PUBLIC   
  3.     "-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"   
  4.     "http://struts.apache.org/dtds/struts-2.1.7.dtd">  
  5. <struts>  
  6.      <package name="csdn" extends="struts-default" namespace="/csdn">  
  7.         <global-results>  
  8.             <result name="input">/index.jsp</result>  
  9.         </global-results>  
  10.            
  11.         <action name="upload" class="cn.csdn.struts2.action.UserAction" method="uploadFile">  
  12.             <!-- 文件保存的文件名称 -->  
  13.             <param name="savePath">/uploads</param>  
  14.             <result name="success">/sc.jsp</result>  
  15.         </action>  
  16.      </package>      
  17. </struts>  
<?xml version="1.0" encoding="UTF-8"?>
 <!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
	"http://struts.apache.org/dtds/struts-2.1.7.dtd">
<struts>
     <package name="csdn" extends="struts-default" namespace="/csdn">
     	<global-results>
     		<result name="input">/index.jsp</result>
     	</global-results>
     	
     	<action name="upload" class="cn.csdn.struts2.action.UserAction" method="uploadFile">
     		<!-- 文件保存的文件名称 -->
     		<param name="savePath">/uploads</param>
     		<result name="success">/sc.jsp</result>
     	</action>
     </package>   
</struts>

 

 

4、下面我们就来看看上传成功的页面:

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics