ajaxfileupload文件上传返回值处理 ajaxfileupload.js + spring mvc文件上传

ajaxfileupload.js组件的确好用,但是那个返回值格式也太恶心了吧!

让人家定义一个dataType:"json",最后给返回一堆html,什么意思?也许是鄙人愚钝,索性修改了下源代码的处理函数,手动返回json得了。

修改代码:

大约在ajaxfileupload.js 的185行左右,有这么个函数:uploadHttpData

原始代码与改后代码对比:

uploadHttpData: function( r, type ) {
        /**原始代码
        var data = !type;
        data = type == "xml" || data ? r.responseXML : r.responseText;
        // If the type is "script", eval it in global context
        if ( type == "script" )
            jQuery.globalEval( data );
        // Get the JavaScript object, if JSON is used.
        if ( type == "json" )
            eval( "data = " + data );
        // evaluate scripts within html
        if ( type == "html" )
            jQuery("
").html(data).evalScripts(); return data; */ // 改后代码 var data =r.responseText; var start = data.indexOf("{"); var end = data.indexOf("}"); var jsonStr = data.substring(start,end+1); return (jsonStr instanceof Object)?jsonStr:eval("(" + jsonStr + ")"); }


就是用来处理了下返回值,这个函数返回的值就直接传递到了我们文件上传的success回调函数json值了。直接当对象使用就ok了。

附带发下文件上传代码吧!


/**
	 * ajax文件上传
	 */
	$("body").on("change","input[name='image']",function(){
		var url = $(this).attr("lang");
		$(".error").ajaxStart(function(){
			$(this).show();
		}).ajaxComplete(function(){
			$(this).hide();
		});
		$.ajaxFileUpload({
			url:url,
			secureuri:false,
			fileElementId:'imageFile',
			success:function(json){
				if(0==json.error){
					$("img[name='imageFile']").attr("src",json.url).show();
				}else{
					$.fn.error(json.message);
				}
			},
			error:function(data,status,e){
				alert(e);
			}
		});
	});

服务器端用的spring mvc,直接返回map就可以了!贴下代码如下:

/**
	 * 系统图:系统内容部分内容图存放在此
	 * @param image
	 * @return
	 */
	@RequestMapping(value="/system",method=RequestMethod.POST)
	@ResponseBody
	public Map system(MultipartFile image){
		return this.upload(image,SettingEnum.image_system_folder,null);
	}

具体上传细节就不赘述了,网上很多,有问题请留言!

你可能感兴趣的:(JavaScript)