利用Jquery的AjaxUpload组件实现头像异步上传并回显

练习中遇到头像上传不能实时显示的问题,利用ajaxUpload异步文件上传解决。

1、导入jquery-1.10.2.min.js、ajaxupload.3.6.js包。

附ajaxupload.3.6.js下载地址:http://download.csdn.net/detail/dengchenlu/3957758

2、jsp中导入包

    


2、jsp中的配置

js:

	//利用AjaxUpload组件实现异步上传头像并回显
    	$(document).ready(function(){
 	  		var button = $("#imgButton");
 	  		new AjaxUpload(button,{
 	  			action:"${basePath}nsfw/user_ajaxUpload.action",
 	  			name:"headImg",//同Action中File文件名,""不能少
 	  			onSubmit: function(file, ext) {  
		            if (!(ext && /^(jpg|JPG|png|PNG|gif|GIF)$/.test(ext))) {  
	               		alert("您上传的图片格式不对,请重新选择!");  
	              		return false;  
           		 	}  
        		}, 
        		onComplete:function(file,response){//默认全成功,不再判断,直接设置img的src
        			var path = "${basePath}upload/";
        			
        			var reg = /(.+)<\/pre>/g;  
				var result = response.match(reg);  
				response = RegExp.$1;//以上三行是为了去除response返回的pre标签内容
					
        			$("#headImg").attr("src",path+response);
        			
        			//由于已经异步设置了头像路径,注册时不再需要重新设置,因此直接隐藏域保存headImg属性
        			$("#imgHidden").val(response);
        		}
 	  		});
    	});


html:

	头像:
            
            	
		           	
 					
            
Action中的接受配置:

//异步显示头像
	public void ajaxUpload(){
		try {
			//处理用户头像
			if(headImg != null){
				String filePath = ServletActionContext.getServletContext().getRealPath("upload/user");//保存路径
				//保存文件名 uuid+后缀
				String fileName = UUID.randomUUID().toString().replace("-", "")+headImgFileName.substring(headImgFileName.lastIndexOf('.'));
				FileUtils.copyFile(headImg,new File(filePath,fileName));
				String headImg = "user/"+fileName;//user/开头
				
				HttpServletResponse response = ServletActionContext.getResponse();
				response.setCharacterEncoding("text/html;charset=UTF-8");
				response.setCharacterEncoding("UTF-8");
				response.getWriter().print(headImg);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
File及setter,getter

	//头像
	private File headImg;
	private String headImgFileName;
	private String headImgContentType;
最终效果:






你可能感兴趣的:(jquery)