上传方法

http://hayageek.com/ajax-file-upload-jquery/



struts上传方法:(来http://ihanfeng.iteye.com/blog/834232)

Struts2本身并没提供上传的组件,我们可以通过调用上传框架来实现文件的上传。

一、配置上传解析器

首先要配置项目的框架,也就是倒导入"struts2-core-2.2.1.jar"库文件,找到org.apache.struts2包下的default.porperties资源文件。如下图;资源文件中给出了不同的strus2的默认配置,我们可看到struts2默认是jakarta作为其文件上传的解析器。


 jakarta是Commo-FileUpload的框架。如果要使用Commo-FileUpload框架来上传文件,只需将"commons-fileupload-1.2.1.jar"和"commons-io-1.3.2.jar"两个jar复制到项目中的WEB-INF/lib目录下就可。

如果想要使用COS框架来上传文件,只需将“cos.jar”复制到项目中就可以,然后在修改struts.multipart.parser常量值。

修改常量值有两种方法,一是在"struts.xml"中修改,代码如下:

<constant name="struts.multipart.paeser" value="cos"></constant>

二是在struts.properties中修改,代码如下:

  sruts.multipart.parser=cos

 

二、实现文件上传的Action

  创建表单:upload.jsp

       <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

Jsp代码   收藏代码
  1. <%  
  2. String path = request.getContextPath();  
  3. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  4. %>  
  5.   
  6. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  7. <html>  
  8.   <head>  
  9.     <base href="<%=basePath%>">  
  10.       
  11.     <title>Struts2文件上传</title>  
  12.       
  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.   
  22.   </head>  
  23.     
  24.   <body>  
  25.    <center>  
  26.     <h1>Struts 2完成上传</h1>  
  27.       <form action="upload.action" method="post" enctype="multipart/form-data">  
  28.         <table>  
  29.             <tr>  
  30.                 <td>用户名:</td>  
  31.                 <td><input type="text" name="username" ></td>  
  32.             </tr>  
  33.             <tr>  
  34.                 <td>上传文件:</td>  
  35.                 <td><input type="file" name="myFile"></td>  
  36.             </tr>  
  37.             <tr>  
  38.                 <td><input type="submit" value="上传"></td>  
  39.                 <td><input type="reset"></td>  
  40.             </tr>  
  41.         </table>  
  42.       </form>  
  43.   </center>  
  44.   </body>  
  45. </html>  

  完成上传Action

package net.hncu.struts2.action;

Java代码   收藏代码
  1. import java.io.File;  
  2. import java.io.FileInputStream;  
  3. import java.io.FileOutputStream;  
  4. import java.io.InputStream;  
  5. import java.io.OutputStream;  
  6.   
  7. import org.apache.struts2.ServletActionContext;  
  8.   
  9. import com.opensymphony.xwork2.ActionSupport;  
  10.   
  11. public class UploadAction extends ActionSupport {  
  12.     // username属性用来封装用户名  
  13.     private String username;  
  14.       
  15.     // myFile属性用来封装上传的文件  
  16.     private File myFile;  
  17.       
  18.     // myFileContentType属性用来封装上传文件的类型  
  19.     private String myFileContentType;  
  20.   
  21.     // myFileFileName属性用来封装上传文件的文件名  
  22.     private String myFileFileName;  
  23.   
  24.       
  25.     //获得username值  
  26.     public String getUsername() {  
  27.         return username;  
  28.     }  
  29.   
  30.     //设置username值  
  31.     public void setUsername(String username) {  
  32.         this.username = username;  
  33.     }  
  34.   
  35.     //获得myFile值  
  36.     public File getMyFile() {  
  37.         return myFile;  
  38.     }  
  39.   
  40.     //设置myFile值  
  41.     public void setMyFile(File myFile) {  
  42.         this.myFile = myFile;  
  43.     }  
  44.   
  45.     //获得myFileContentType值  
  46.     public String getMyFileContentType() {  
  47.         return myFileContentType;  
  48.     }  
  49.   
  50.     //设置myFileContentType值  
  51.     public void setMyFileContentType(String myFileContentType) {  
  52.         this.myFileContentType = myFileContentType;  
  53.     }  
  54.   
  55.     //获得myFileFileName值  
  56.     public String getMyFileFileName() {  
  57.         return myFileFileName;  
  58.     }  
  59.   
  60.     //设置myFileFileName值  
  61.     public void setMyFileFileName(String myFileFileName) {  
  62.         this.myFileFileName = myFileFileName;  
  63.     }  
  64.   
  65.     public String execute() throws Exception {  
  66.           
  67.         //基于myFile创建一个文件输入流  
  68.         InputStream is = new FileInputStream(myFile);  
  69.           
  70.         // 设置上传文件目录  
  71.         String uploadPath = ServletActionContext.getServletContext()  
  72.                 .getRealPath("/upload");  
  73.           
  74.         // 设置目标文件  
  75.         File toFile = new File(uploadPath, this.getMyFileFileName());  
  76.           
  77.         // 创建一个输出流  
  78.         OutputStream os = new FileOutputStream(toFile);  
  79.   
  80.         //设置缓存  
  81.         byte[] buffer = new byte[1024];  
  82.   
  83.         int length = 0;  
  84.   
  85.         //读取myFile文件输出到toFile文件中  
  86.         while ((length = is.read(buffer)) > 0) {  
  87.             os.write(buffer, 0, length);  
  88.         }  
  89.         System.out.println("上传用户"+username);  
  90.         System.out.println("上传文件名"+myFileFileName);  
  91.         System.out.println("上传文件类型"+myFileContentType);  
  92.         //关闭输入流  
  93.         is.close();  
  94.           
  95.         //关闭输出流  
  96.         os.close();  
  97.           
  98.         return SUCCESS;  
  99.     }  
  100.   
  101. }  

  配置上传Action

   <?xml version="1.0" encoding="UTF-8" ?>

Java代码   收藏代码
  1. <!DOCTYPE struts PUBLIC  
  2.     "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"  
  3.     "http://struts.apache.org/dtds/struts-2.0.dtd">  
  4. <struts>  
  5.   
  6.     <package name="struts2" extends="struts-default">  
  7.         <action name="upload" class="net.hncu.struts2.action.UploadAction">  
  8.             <result name="success">/result.jsp</result>  
  9.             <result name="input">/upload.jsp</result>  
  10.         </action>  
  11.     </package>  
  12.   
  13.     <!-- Add packages here -->  
  14.   
  15. </struts>  

  测试页面:


ajax上传方法

下载ajaxFileUpload控件,使用方法如下:

在jsp页面上:

<table style="margin-top:20px;" class="table-style-default">
<tr>
<td class="upload-text-sty-long" >身份证正面扫描件<div class="upload-text-warn">*图片格式JPG或BMP / 大小不超过300K</div></td>
<td style="width:150px"><input type="file" name="f_idfront" id="idfront" /></td>
<td style="text-align:left;"><input  type="button" onclick="Util.piIDFrontUpload('idfront')" id="uploadbtn1" value="上传" /><span style="white-space:pre">		</span><span id="chenggongdiv1" style="width:70px;font:12px;margin-left:15px;color:red;visibility:hidden" >上传成功</span>
	<input type="hidden" name="status" id="status1" value="${status[0]}"/>
</td>
</tr>
</table>
在js里调用 ajaxFileUpload的控件


var Util = {
piIDFrontUpload:function(fileid){
		$.ajaxFileUpload({
			url:'apply/memberupload!piIDFrontUpload',
			secureuri:false,
			fileElementId:fileid,
			dataType:'json',
			success:function(data){
				if(data.error){
					$('#uploadbtn1').val("重传");
					$('#status1').val("0");
					$('#chenggongdiv1').css({"visibility":"hidden"});
					alert(data.error);
				}else{
					$('#uploadbtn1').val("重传");
					$('#status1').val("1");
					$('#chenggongdiv1').css({"visibility":"visible"});
				}
			}
		});
	}
}
发送到Action中,可以在该Action中进行文件检验,文件保存

package com.yuhong.see.action.apply;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;

import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.opensymphony.xwork2.Action;
import com.yuhong.see.action.BaseAction;
import com.yuhong.see.util.Constant;
import com.yuhong.see.util.ProjectUtils;
import com.yuhong.see.util.StringConverter;
import com.yuhong.see.ws.bean.UserFileSubmitReq;

/**上传文件ACTION
 * 代码编写人:方正逸
 * 
 * **/
@Component
@Scope("prototype")
public class MemberUploadAction extends BaseAction{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1755276267613099344L;

	//需要上传的文件
	private File f_idfront;
	private String f_idfrontContentType;// 上传文件类型
	private String f_idfrontFileName;// 上传头像文件名称
	private String ext;// 保存文件后缀
	private String message;
	private boolean verification=true;
	//ajax 输出流-------------------------------------------------------------------------
	private InputStream textmessage;

	private static String Upd = StringConverter.getDateTimeToString(new Date()).substring(0,8);
	// 生成随机不重复文件名
	public String GenerateDistinctFileName(String getname) {
		String path = ServletActionContext.getServletContext().getRealPath(Constant.FILE_PATCH);
		return ProjectUtils.generateDistinctFileName(path, this.getExt(getname));
	}

	// 保存文件方法
	public String pisaveFile(File file,String newname,String getname){
		if (file!=null) {
			String filename=newname+GenerateDistinctFileName(getname);
			String path = ServletActionContext.getServletContext().getRealPath(
			Constant.FILE_PATCH)+"\\"+Upd;
			if(pisaveFile(file, path, filename,newname,getname))
				//this.realpath=path+"\\"+filename;
				return filename;
		}
		return null;
	}
	
	// 保存文件,成功后返回保存路径,失败返回null
	public boolean pisaveFile(File file, String path, String filename,String newname,String getname) {
		try {
			if (file != null) {
				InputStream is = new FileInputStream(file);
				File checkpath = new File(path);
				//判断路径是否存在。如果不存在则创建
				if (!checkpath.exists()) 
			    {   
					checkpath.mkdir();  
			    }
				File outfile = new File(path, filename);
			   
				OutputStream os = new FileOutputStream(outfile);
				byte[] buffer = new byte[400];
				int length = 0;
				while ((length = is.read(buffer)) != -1) {
					os.write(buffer, 0, length);
				}
				is.close();
				os.close();
				
				//保存对象到SESSION
				pisaveSession(filename,path,newname,getname);
			}

		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		System.out.println("file name is :" + filename);
		return true;
	}
	//个人投资者放入SESSION步骤
	private void pisaveSession(String filename,String path,String type,String getname)
	{
		UserFileSubmitReq userfile = new UserFileSubmitReq();		
		HashMap hash= (HashMap)getSession().getAttribute("pifile");
		if(hash == null)
		{
			hash = new HashMap();
		}
		if(type.equals("idpos")||type.equals("idneg")||type.equals("assertc")||type.equals("ty"))
		{
			userfile.setFileCode(filename.replace(".jpg","").replace(".jpeg", "").replace(".bmp", ""));
			userfile.setFileName(getname.replaceAll(".jpg", "").replaceAll(".jpeg", "").replace(".bmp", ""));
		}
		
		userfile.setFileType("."+getExt(getname));
		//推荐会员专用
		userfile.setFileUse("03");
		userfile.setInpath(path+"\\"+filename);
		hash.put(type,userfile);
		
		
		getSession().setAttribute("pifile",hash);
		HashMap x=new HashMap();
		x=(HashMap)getSession().getAttribute("pifile");
		
	}
	//推荐机构会员入会申请书验证上传信息-------------------------------------------------------------------------
	public void verifyRar(String getname,File file){
		// 验证上传文件
		if (file != null&&getname!=null) {			
			if (!ProjectUtils.isRarTypeAllowed(this.getExt(getname))) {
				//文件类型不正确
				if(this.message!=null){
					this.message=this.message+",\"error\":\"上传文件类型错误!\"";
				}else{
					this.message="\"error\":\"上传文件类型错误!\"";
				}
				this.setVerification(false);
			} else {
				if (file.length() > (1024 * 1024 * 5)) {
					//文件超过5M
					if(this.message!=null){
						this.message=this.message+",\"error\":\"文件超出指定大小!\"";
					}else{
						this.message="\"error\":\"文件超出指定大小!\"";
					}
					this.setVerification(false);
				}
			}
		}else{
			//没有上传文件
			if(this.message!=null){
				this.message=this.message+",\"error\":\"没有上传文件!\"";
			}else{
				this.message="\"error\":\"没有上传文件!\"";
			}
			this.setVerification(false);
		}
	}
<span style="white-space:pre">	</span>// 验证RAR类型是否被允许
<span style="white-space:pre">	</span>public static boolean isRarTypeAllowed(String ext) {
<span style="white-space:pre">		</span>String[] allowed = {"rar","zip"};
<span style="white-space:pre">		</span>int i = 0;
<span style="white-space:pre">		</span>for (i = 0; i < allowed.length; i++) {
<span style="white-space:pre">			</span>if (allowed[i].equalsIgnoreCase(ext)) {
<span style="white-space:pre">				</span>break;
<span style="white-space:pre">			</span>}
<span style="white-space:pre">		</span>}
<span style="white-space:pre">		</span>if (i == allowed.length) {
<span style="white-space:pre">			</span>return false;
<span style="white-space:pre">		</span>}
<span style="white-space:pre">		</span>return true;
<span style="white-space:pre">	</span>}
	//验证JPG文件-------------------------------------------------------------------------
	public void verifyJpg(String getname,File file){
		// 验证上传文件
	
		if (file != null&&getname!=null) {
			
			if (!ProjectUtils.isJpgTypeAllowed(this.getExt(getname))) {
				//文件类型不正确
				if(this.message!=null){
					this.message=this.message+",\"error\":\"上传文件类型错误!\"";
				}else{
					this.message="\"error\":\"上传文件类型错误!\"";
				}
				this.setVerification(false);
			} else {
				if (file.length() > (1024 * 300)) {
					//文件超过300K
					if(this.message!=null){
						this.message=this.message+",\"error\":\"文件超出指定大小!\"";
					}else{
						this.message="\"error\":\"文件超出指定大小!\"";
					}
					this.setVerification(false);
				}
			}
		}else{
			//没有上传文件
			if(this.message!=null){
				this.message=this.message+",\"error\":\"没有上传文件!\"";
			}else{
				this.message="\"error\":\"没有上传文件!\"";
			}
			this.setVerification(false);
		}
	}
<span style="white-space:pre">	</span>// 验证文件类型是否被允许
<span style="white-space:pre">	</span>public static boolean isJpgTypeAllowed(String ext) {
<span style="white-space:pre">		</span>String[] allowed = {"jpg","jpeg","bmp"};
<span style="white-space:pre">		</span>int i = 0;
<span style="white-space:pre">		</span>for (i = 0; i < allowed.length; i++) {
<span style="white-space:pre">			</span>if (allowed[i].equalsIgnoreCase(ext)) {
<span style="white-space:pre">				</span>break;
<span style="white-space:pre">			</span>}
<span style="white-space:pre">		</span>}
<span style="white-space:pre">		</span>if (i == allowed.length) {
<span style="white-space:pre">			</span>return false;
<span style="white-space:pre">		</span>}
<span style="white-space:pre">		</span>return true;
<span style="white-space:pre">	</span>}
	//验证DOC文件信息-------------------------------------------------------------------------
	public void verify(String filename,String getname,File file){
		// 验证上传文件
	
		if (file != null&&getname!=null) {
			if(!filename.equals(getname.replaceAll(".docx", "").replaceAll(".doc", ""))){
				if(this.message!=null){
					this.message=this.message+",\"error\":\"上传文件名错误!\"";
				}else{
					this.message="\"error\":\"上传文件名错误!\"";
				}
				this.setVerification(false);
			}
			if (!ProjectUtils.isDocTypeAllowed(this.getExt(getname))) {
				//文件类型不正确
				if(this.message!=null){
					this.message=this.message+",\"error\":\"上传文件类型错误!\"";
				}else{
					this.message="\"error\":\"上传文件类型错误!\"";
				}
				this.setVerification(false);
			} else {
				if (file.length() > (1024 * 1024 * 2)) {
					//文件超过2M
					if(this.message!=null){
						this.message=this.message+",\"error\":\"文件超出指定大小!\"";
					}else{
						this.message="\"error\":\"文件超出指定大小!\"";
					}
					this.setVerification(false);
				}
			}
		}else{
			//没有上传文件
			if(this.message!=null){
				this.message=this.message+",\"error\":\"没有上传文件!\"";
			}else{
				this.message="\"error\":\"没有上传文件!\"";
			}
			this.setVerification(false);
		}
	}
	// 验证DOC文件类型是否被允许
<span style="white-space:pre">	</span>public static boolean isDocTypeAllowed(String ext) {
<span style="white-space:pre">		</span>String[] allowed = {"doc","docx"};
<span style="white-space:pre">		</span>int i = 0;
<span style="white-space:pre">		</span>for (i = 0; i < allowed.length; i++) {
<span style="white-space:pre">			</span>if (allowed[i].equalsIgnoreCase(ext)) {
<span style="white-space:pre">				</span>break;
<span style="white-space:pre">			</span>}
<span style="white-space:pre">		</span>}
<span style="white-space:pre">		</span>if (i == allowed.length) {
<span style="white-space:pre">			</span>return false;
<span style="white-space:pre">		</span>}
<span style="white-space:pre">		</span>return true;
<span style="white-space:pre">	</span>}
	//身份证正面扫描件上传
	public String piIDFrontUpload()
	{
		try {
/**		    //验证信息有效性
			this.verifyJpg(f_idfrontFileName,f_idfront);
			
			if(this.verification){
				//保存文件**/
				String srcurl=pisaveFile(f_idfront,"idpos",f_idfrontFileName);
				if(srcurl!=null){
						this.message="\"srcurl\":\""+srcurl+"\"";
				}
/**			}**/
			if(this.message!=null){
				this.message="{"+this.message+"}";
				
			}
			textmessage=new ByteArrayInputStream(message.getBytes("GBK"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
		return Action.SUCCESS;
	}	
	public String getExt(String filename) {
		if (ext == null&&filename!=null) {
			ext = filename
					.substring(filename.lastIndexOf(".") + 1);
		}
		return ext;
	}	
<span style="white-space:pre">	</span>// 生成随机不重复文件名
<span style="white-space:pre">	</span>public static String generateDistinctFileName(String path, String ext) {
<span style="white-space:pre">		</span>String FileName;
<span style="white-space:pre">		</span>File file;
<span style="white-space:pre">		</span>do {
<span style="white-space:pre">			</span>FileName = getRandomName() + "." + ext;
<span style="white-space:pre">			</span>file = new File(path, FileName);
<span style="white-space:pre">		</span>} while (file.exists());
<span style="white-space:pre">		</span>return FileName;
<span style="white-space:pre">	</span>}
	public boolean isVerification() {
		return verification;
	}
	public void setVerification(boolean verification) {
		this.verification = verification;
	}
	public File getF_idfront() {
		return f_idfront;
	}
	public void setF_idfront(File f_idfront) {
		this.f_idfront = f_idfront;
	}
	public String getF_idfrontContentType() {
		return f_idfrontContentType;
	}
	public void setF_idfrontContentType(String f_idfrontContentType) {
		this.f_idfrontContentType = f_idfrontContentType;
	}
	public String getF_idfrontFileName() {
		return f_idfrontFileName;
	}
	public void setF_idfrontFileName(String f_idfrontFileName) {
		this.f_idfrontFileName = f_idfrontFileName;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值