jquery File Upload 插件应用之解析返回json对象

后端用spring mvc+module:

Controller:

@AuthPassport
	@RequestMapping("/EAF301L1/upload/{appno}/{rev}")
	public @ResponseBody String uploadFile(HttpServletRequest request,@PathVariable("appno")String pvAppNo,@PathVariable("rev") String pvRevNo) {
		JSONData lvRet=new JSONData();
		HashMap<String, FileItem>  lvFiles=new HashMap<String, FileItem> ();
		try {
			Map<String,Object>lvT= HttpBeanUtil.beanFromUrlRequestByJson(HashMap.class, new TypeReference<HashMap>() {
			}, request, lvFiles);			
			if (lvFiles!=null){
				module.uploadFiles(pvAppNo, pvRevNo, lvFiles, getCurrLogin(request), getLocale(request));
			}
		} catch (Exception e) {
			BaseModule.jsonDataFillErrMsg(lvRet, e);
		}
		return lvRet.toString();
	}

Module, 不知道为什么,后台用apache的fileupload 限制文件大小无效,只有在下面方法一开始就自己检查一下,如果超过限制就抛出异常,Controller捕获然后通过json格式返回.

/****
	 * 上传文件处理
	 * @param pvAppNo
	 * @param pvRev
	 * @param pvFiles
	 * @throws ModifyDataException 
	 */
	public void uploadFiles(String pvAppNo,String pvRev,HashMap<String, FileItem>pvFiles,String pvLogin,Locale pvLocale) throws ModifyDataException{
		for (Entry<String, FileItem>item:pvFiles.entrySet()){
			if (item.getValue().getSize()>(EAFSetting.c_upload_max_size*1024*1024)){
				throw new ModifyDataException(MessageSourceHelper.getMessage("MSG30106",new Object[]{EAFSetting.c_upload_max_size},"", pvLocale));
			}
		}
		for (Entry<String, FileItem>item:pvFiles.entrySet()){
			String lvDestPath=EAFSetting.c_appfs_dir+"/"+pvAppNo+"/"+pvRev;
			File lvT=new File(lvDestPath);
			if (!lvT.exists()){
				lvT.mkdirs();
			}
			String lvFileName=String.valueOf(ContextHolder.getJdbcTemplate().queryForObject("select nextval('tl_attachment_filename_seq')", Long.class));
			lvDestPath=lvDestPath+"/"+lvFileName;
			try{
				FileUploadModule.saveFileItem(item.getValue(), lvDestPath);
			}
			catch (Exception e){
				throw new ModifyDataException(MessageSourceHelper.getMessage("MSG30105",new Object[]{e.getMessage()},"", pvLocale));
			}
			TlAttachment lvNew=new TlAttachment();
			lvNew.setFlAppNo(pvAppNo);
			lvNew.setFlRevision(pvRev);
			lvNew.setFlAttachmentName(lvFileName);
			lvNew.setFlAttachmentDesc(item.getValue().getName());
			try {
				setModifyLog(pvLogin, lvNew, false);
			} catch (Exception e) {
			}
			try {
				mvTlAttachDao.save(lvNew, true);
			} catch (ModifyDataException e) {
				mvTlAttachDao.clear();
				throw new ModifyDataException(e.getMessage());
			}
		}
	}




   前端 :

<%@page import="com.freestyle.common.utils.Util"%>
<%
	/* --------------------------------------------------------------------
	Program:    EAF301 Prepare Eng Approval Form
	  Created:    5/Oct/2016 by rock
	 * -------------------------------------------------------------------- */
%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ page isELIgnored="false"%>

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ taglib uri="http://www.freestyle.com/jsp/tag/ns" prefix="ns"%>
<%@ taglib uri="http://www.freestyle.com/jsp/tag/bs" prefix="bs"%>
<%@ taglib uri="http://www.freestyle.com/jsp/tag/fs" prefix="fs"%>
<%@ taglib uri="http://www.freestyle.com/jsp/tag/cm" prefix="cm"%>

<%@page import="com.freestyle.common.spring.MessageSourceHelper"%>
<%@ include file="eafdef.jsp"%>
<%@ include file="common/alco_lib.jsp"%>
<%@ include file="common/alco_access.jsp"%>
<?xml version="1.0" encoding="utf-8"?>
<%
   String pvAppNo=Util.fillNullStr(request.getParameter("appno"));
   String pvRev=Util.fillNullStr(request.getParameter("rev"));
   if (pvAppNo.equals("")||pvRev.equals("")){
	   return;
   }
%>
<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="zh" lang="zh">

<!--[if IE 8]> <html lang="utf8" class="ie8 no-js"> <![endif]-->

<!--[if IE 9]> <html lang="utf8" class="ie9 no-js"> <![endif]-->

<!--[if !IE]><!-->
<html lang="utf8" class="no-js">
<!--<![endif]-->

<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=8">
<meta name=viewport content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="media/css/bootstrap.min.css">
<link href="media/css/bootstrap-responsive.min.css" rel="stylesheet"
	type="text/css" />

<link rel="stylesheet" type="text/css" href="js/style.css" />
<link href="media/css/style-metro.css" rel="stylesheet" type="text/css" />
<link href="media/css/style.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" href="media/ext/common.css" />
<link rel="stylesheet" href="media/css/font-awesome.min.css" />
<script src="media/js/jquery-1.10.1.min.js" type="text/javascript"></script>
<!-- 
<script src="media/js/jquery-migrate-1.2.1.min.js"
	type="text/javascript"></script>
 -->
<script type="text/javascript" src="media/js/jquery.bootpag.min.js"></script>
<script type="text/javascript" src="media/ext/browser.js"></script>
</head>
<body>

	<div class="portlet" style="margin-bottom:0px">
		<div class="portlet-title" style="margin-bottom:0px">
			<div class="caption">
				<i class="icon-file"></i>Attachments
			</div>
		</div>

		<div class="portlet-body">
			<table
				class="table table-striped table-bordered table-advance table-hover">
				<thead>
					<tr>
						<th>ID</th>
						<th>Attachment</th>
						<th>Remove</th>
					</tr>
				</thead>
				<tbody>
					<tr>
						<td class="highlight">
							1
						</td>
						<td ><a >Mike Nilson</a> </td>
						<td> <input type="checkbox" name="files" value="2" />
						</td>
					</tr>					
				</tbody>
			</table>
		</div>
	</div>
	<div class="row-fluid" >
		<div id="weixin_progress" style="height: 20px;background-color: #FBDD9F;display: none;vertical-align: middle;text-align: center;"></div>
		<input type="file" multiple="multiple" name="file_upload" id="file_upload" alt="Select file to upload ..."/>
		<!-- <input type="text" name="ed_desc" id="ed_desc" maxlength="255" style="margin-bottom: 0px"/>
		<button class="btn btnUpload">Upload</button> -->
	</div>

	<script>
	var mvApp="<%=pvAppNo%>";
	var mvRev="<%=pvRev%>";
		$(document).ready(function() {			  
			    $("#file_upload").fileupload({  
			            url: './EAF301L1/upload/{0}/{1}'.format(mvApp,mvRev),
			            /*formData:{desc:$("#ed_desc").val()},*/
			            sequentialUploads: true  
			        }).bind('fileuploadprogress', function (e, data) {  
			            var progress = parseInt(data.loaded / data.total * 100, 10);  
			            $("#weixin_progress").show().css('width',progress + '%');  
			            $("#weixin_progress").html(progress + '%');  
			        }).bind('fileuploaddone', function (e, data) {
			        	var lvContent="";
			        	if (typeof data.result!="string"){
			        		lvContent=data.result[0].body.innerText;
			        	}
			        	else{
			        		lvContent=data.result;
			        	}
			        	var lvRet=eval('('+lvContent+')');
			        	if (lvRet.errCode!=0){
			        		alert(lvRet.errMsg);
			        		return;
			        	}
			           // $("#weixin_show").attr("src","__PUBLIC__/"+data.result);  
			            $("#weixin_progress").hide();//css({display:"none"});  
			            //$("#weixin_cancle").css({display:""});  
			        });  			             			 
			$(".btnUpload").click(function(){
				
			});
		});
	</script>
	<script src="media/js/bootstrap.min.js" type="text/javascript"></script>
	<script type="text/javascript"
		src="media/ext/jquery.serialize-object.js"></script>
	<script type="text/javascript" src="media/ext/jquery.placeholder.js"></script>
	<link rel="stylesheet" href="media/ext/jquery-ui-1.10.4.custom.min.css" />
	<script src="media/ext/jquery-ui-1.10.4.custom.min.js"
		type="text/javascript"></script>
	<!-- -最新的jquery-ui的autocomplete不兼容IE8 -->

	<link rel="stylesheet" href="media/ext/jquery.fileupload.css" />
	<link rel="stylesheet" href="media/ext/jquery.fileupload-ui.css" />
	<script type="text/javascript" src="media/ext/jquery.fileupload.js"></script>
	<script type="text/javascript" src="media/ext/common_ext.js"></script>
	<script type="text/javascript"
		src="media/ext/jquery.iframe-transport.js"></script>

</body>
</html>

现在重点说一下前端的jquery file upload插件, 它对chrome和IE8两种浏览器在上传结束后返回的数据结构不一样,chrome的话,data.result就是返回的json字符串了,而IE,data.result则是一个对象, data.result[0].body里面装的是body dom对象, 而可怜的json字符需要通过这个body的innerText属性取得.

重点:

var lvContent="";
			        	if (typeof data.result!="string"){
			        		lvContent=data.result[0].body.innerText;
			        	}
			        	else{
			        		lvContent=data.result;
			        	}
			        	var lvRet=eval('('+lvContent+')');
			        	if (lvRet.errCode!=0){
			        		alert(lvRet.errMsg);
			        		return;
			        	}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值