Strut2实现上传

JAVA Web 之 struts2文件上传下载演示(一)

 

 

一、文件上传演示

 

1.需要的jar包

    大多数的jar包都是struts里面的,大家把jar包直接复制到WebContent/WEB-INF/lib目录下面即可,需要的jar包如下图所示,其中的javax.servlet.jar是额外添加的,我到网上随便搜了一个下载地址http://ishare.iask.sina.com.cn/f/19185878.html?retcode=0,当然附件里面也有


 

2.配置web.xml

   配置WebContent/WEB-INF/web.xml中的内容,如果你的项目已经配置好了struts,这步可以跳过.

Xml代码 复制代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">  
  3.   <display-name>UpDownDemo</display-name>  
  4.      
  5.   <!-- 配置struts2 -->  
  6.   <filter>  
  7.     <filter-name>struts2</filter-name>  
  8.     <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>  
  9.   </filter>  
  10.   <!-- 所有类型的请求都会被struts拦截 -->  
  11.   <filter-mapping>  
  12.     <filter-name>struts2</filter-name>  
  13.     <url-pattern>/*</url-pattern>  
  14.   </filter-mapping>  
  15.      
  16.   <welcome-file-list>  
  17.     <welcome-file>index.jsp</welcome-file>  
  18.   </welcome-file-list>  
  19. </web-app>  

 

 

3.Web界面

    其中有一点是特别需要注意的:定义form的时候,一定要添加enctype="multipart/form-data",并且一定要设置method="post"。

示例<form action="upload" enctype="multipart/form-data" method="post">

Html代码 复制代码  收藏代码
  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>文件上传演示</title>  
  8. </head>  
  9. <body>  
  10.     <div align="center">  
  11.         <form action="upload" enctype="multipart/form-data" method="post">  
  12.             请选择文件<br>  
  13.             <input type="file" name="file">  
  14.             <br><br>  
  15.             <input type="submit" value="确认上传">  
  16.         </form>  
  17.     </div>  
  18. </body>  
  19. </html>  
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>文件上传演示</title>
</head>
<body>
	<div align="center">
		<form action="upload" enctype="multipart/form-data" method="post">
			请选择文件<br>
			<input type="file" name="file">
			<br><br>
			<input type="submit" value="确认上传">
		</form>
	</div>
</body>
</html>

 

 

4.后台JAVA代码

    代码中有解析

Java代码 复制代码  收藏代码
  1. package action;   
  2.   
  3. import java.io.File;   
  4. import java.io.IOException;   
  5. import java.io.Serializable;   
  6.   
  7. import org.apache.commons.io.FileUtils;   
  8. import org.apache.struts2.ServletActionContext;   
  9.   
  10. import util.Encrypter;   
  11.   
  12. import com.opensymphony.xwork2.ActionSupport;   
  13.   
  14. /**  
  15.  * @author Kingt.W  
  16.  */  
  17. @SuppressWarnings("serial")   
  18. public class FileAction extends ActionSupport implements Serializable {   
  19.     /*  
  20.      * 这里定义的变量,一定要跟网页的<input type="file" name="file">中的name属性的值一致. 
  21.      * 如果网页中定义的是<input type="file" name="img">,那么在这里就要定义File img; 
  22.      */  
  23.     private File file;   
  24.     /*  
  25.      * 这里定义的fileFileName一定要是xxxFileName的形式,否则无法取到文件的文件名. 
  26.      * 其中xxx必须与上面定义的File类型的变量一致,如果上面定义的是File img,那么这里就 
  27.      * 定义为String imgFileName  
  28.      */  
  29.     private String fileFileName;   
  30.     /*  
  31.      * 这里定义的是文件的类型,如果不需要获取文件类型的话,可以不定义.  
  32.      *  命名规则跟xxxFileName类似,这里一定要定义成xxxContentType形式. 
  33.      */  
  34.     private String fileContentType;   
  35.     /*  
  36.      * 这这个变量是重命名后的文件名  
  37.      */  
  38.     private String newFileName;   
  39.        
  40.     //getters and setters我省略了,没有复制上来   
  41.   
  42.     public String upload() {   
  43.         System.out.println("文件名:" + fileFileName);   
  44.         System.out.println("文件类型:" + fileContentType);   
  45.            
  46.         if (file != null) {   
  47.             //文件的保存路径是WebContent/file目录下   
  48.             String realpath = ServletActionContext.getServletContext()   
  49.                     .getRealPath("/file");   
  50.             System.out.println("文件的保存路径:" + realpath);   
  51.                
  52.             //文件的后缀   
  53.             String suffix = fileFileName.substring(fileFileName   
  54.                     .lastIndexOf("."));   
  55.             if (fileFileName.lastIndexOf(".") == -1) {   
  56.                 return INPUT;   
  57.             }   
  58.                
  59.             //上传以后,会重命名文件的名称,将其命名为全部是数字的文件名,防止可能出现的乱码.  
  60.             //当然, 只是为了防止出现乱码,一般不会出现乱码   
  61.             newFileName = Encrypter.randFileName() + suffix;    
  62.                
  63.             File savefile = new File(new File(realpath), newFileName);   
  64.             //如果保存的路径不存在,则新建   
  65.             if (!savefile.getParentFile().exists())   
  66.                 savefile.getParentFile().mkdirs();   
  67.   
  68.             try {   
  69.                 //复制文件   
  70.                 FileUtils.copyFile(file, savefile);   
  71.                 System.out.println("文件上传成功");   
  72.             } catch (IOException e) {   
  73.                 e.printStackTrace();   
  74.                 System.out.println("文件上传失败");   
  75.                 return INPUT;   
  76.             }   
  77.         }   
  78.            
  79.         return SUCCESS;   
  80.     }   
  81. }  
package action;

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

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

import util.Encrypter;

import com.opensymphony.xwork2.ActionSupport;

/**
 * @author Kingt.W
 */
@SuppressWarnings("serial")
public class FileAction extends ActionSupport implements Serializable {
	/*
	 * 这里定义的变量,一定要跟网页的<input type="file" name="file">中的name属性的值一致.
	 * 如果网页中定义的是<input type="file" name="img">,那么在这里就要定义File img;
	 */
	private File file;
	/*
	 * 这里定义的fileFileName一定要是xxxFileName的形式,否则无法取到文件的文件名.
	 * 其中xxx必须与上面定义的File类型的变量一致,如果上面定义的是File img,那么这里就
	 * 定义为String imgFileName
	 */
	private String fileFileName;
	/*
	 * 这里定义的是文件的类型,如果不需要获取文件类型的话,可以不定义.
	 *  命名规则跟xxxFileName类似,这里一定要定义成xxxContentType形式.
	 */
	private String fileContentType;
	/*
	 * 这这个变量是重命名后的文件名
	 */
	private String newFileName;
	
	//getters and setters我省略了,没有复制上来

	public String upload() {
		System.out.println("文件名:" + fileFileName);
		System.out.println("文件类型:" + fileContentType);
		
		if (file != null) {
			//文件的保存路径是WebContent/file目录下
			String realpath = ServletActionContext.getServletContext()
					.getRealPath("/file");
			System.out.println("文件的保存路径:" + realpath);
			
			//文件的后缀
			String suffix = fileFileName.substring(fileFileName
					.lastIndexOf("."));
			if (fileFileName.lastIndexOf(".") == -1) {
				return INPUT;
			}
			
			//上传以后,会重命名文件的名称,将其命名为全部是数字的文件名,防止可能出现的乱码.
			//当然, 只是为了防止出现乱码,一般不会出现乱码
			newFileName = Encrypter.randFileName() + suffix; 
			
			File savefile = new File(new File(realpath), newFileName);
			//如果保存的路径不存在,则新建
			if (!savefile.getParentFile().exists())
				savefile.getParentFile().mkdirs();

			try {
				//复制文件
				FileUtils.copyFile(file, savefile);
				System.out.println("文件上传成功");
			} catch (IOException e) {
				e.printStackTrace();
				System.out.println("文件上传失败");
				return INPUT;
			}
		}
		
		return SUCCESS;
	}
}
 

 

5.配置struts.xml

 

Xml代码 复制代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">  
  3. <struts>  
  4.     <package name="struts" namespace="/" extends="struts-default">  
  5.         <action name="upload" class="action.FileAction" method="upload">  
  6.             <result name="success">download.jsp</result>  
  7.             <result name="input">download.jsp</result>  
  8.         </action>  
  9.     </package>  
  10. </struts>  
 

 

6.小注

    至此,文件上传的功能就实现了。

 

    <1>文件下载演示,请查看另一篇博客

 http://blog.csdn.net/red_titan/article/details/7843279 

    <2>由于我是在J2EE Eclipse下建的项目,所以如果大家把附件下载以后,导入J2EE Eclipse是可以直接运行的,导入其他的IDE应该是没法直接运行,但是可以先新建好项目以后,把我的项目中的文件放到对应的目录下面即可

 

    <3>效果图如下

    选择文件,然后点击【确认上传】


 

    上传文件的内容如下图所示


 

然后就可以在 eclipse工作空间\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\UpDownDemo\file下面找到刚刚上传的文件了。

打开文件,发现两个记事本中的内容一样(在java代码中我有解释为啥会把文件重命名)


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值