600字范文,内容丰富有趣,生活中的好帮手!
600字范文 > jQuery插件之ajaxFileUpload异步上传

jQuery插件之ajaxFileUpload异步上传

时间:2020-10-06 04:13:58

相关推荐

jQuery插件之ajaxFileUpload异步上传

介绍

AjaxFileUpload.js 是一个异步上传文件的jQuery插件,原理是创建隐藏的表单和iframe然后用JS去提交,获得返回值。

下载地址:

/files/kissdodog/ajaxfileupload_JS_File.rar/blog/2123021

属性

错误提示

例子

脚本:

<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery.js"></script><script type="text/javascript" src="${pageContext.request.contextPath}/js/ajaxfileupload.js"></script><script>/*** 异步上传图片*/$(function () {$("#saveImg").click(function () {//效验上传图片类型var ths=$('#fileImg');if (ths.val().length <= 0) {alert("请上传图片");return false;} else if(!/\.(gif|jpg|jpeg|png|GIF|JPG|PNG)$/.test(ths.val())){alert("图片类型必须是.gif,jpeg,jpg,png中的一种");ths.val("");return false;}//效验成功调用异步上传函数ajaxFileUpload();return true;})})/*** ajaxFileUpload JQuery异步上传插件*/function ajaxFileUpload() {$.ajaxFileUpload({url: realPath+"/whiteListRule/saveImg.htm", //用于文件上传的服务器端请求地址type: 'post',data: { gameId: gameId },secureuri: false, //是否需要安全协议,一般设置为falsefileElementId: 'fileImg', //文件上传域的IDdataType: 'text', //返回值类型 一般设置为jsonsuccess: function (data, status) //服务器成功响应处理函数{var data=eval("("+data+")")if (typeof (data.error) != 'undefined') {if (data.error != '') {alert(data.error);} else {alert(data.msg);$("#img1").attr("src", data.imgurl);}}},error: function (data, status, e)//服务器响应失败处理函数{alert(e);}})return false;}</script>

控制器:

package com.shiliu.game.controller;import java.awt.image.BufferedImage;import java.io.File;import java.io.FileInputStream;import javax.annotation.Resource;import javax.imageio.ImageIO;import javax.servlet.http.HttpServletRequest;import org.apache.log4j.Logger;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.ResponseBody;import org.springframework.web.multipart.MultipartFile;import com.mon.Constant;import com.shiliu.game.domain.Game;import com.shiliu.game.service.IGameService;import com.shiliu.game.utils.PropertyUtil;import com.shiliu.game.utils.ReadProperties;/*** 异步上传控制器* @author wkr* @Date -12-12**/@Controller@RequestMapping(value = "/whiteListRule")public class WhiteListRuleController {//log4jprivate Logger log =Logger.getLogger(AddCustomerDataController.class);//存储图片路径private String fileUploadPath = PropertyUtil.getProperty("file_upload");//读取图片路径private String fileReadPath = PropertyUtil.getProperty("file_url");@Resourceprivate IGameService gameService; //Game/*** 上传图片* @param gameId 参数* @param multipart 文件* @param request* @return*/@RequestMapping(value="/saveImg")@ResponseBodypublic String saveImgMethod(@RequestParam(value = "gameId") String gameId,@RequestParam(value="fileImg") MultipartFile multipart,HttpServletRequest request){String path = null;File upload = null;//已经保存文件的全路径String img = null;//存储数据库路径String readPath = null;//读取路径//返回信息String msg = "";String error = "";try {//存储路径path = fileUploadPath + Constant.FILE_PATH;//存储本地文件夹upload = ReadProperties.upload(multipart, path);//存储数据库路径img = Constant.FILE_PATH + "/" + upload.getName();//读取路径readPath = fileReadPath + Constant.FILE_PATH + "/" + upload.getName();//限制图片大小int ruleHeight = 400;int ruleWidth = 750;int deviation = 100;//误差 BufferedImage sourceImg = ImageIO.read(new FileInputStream(upload));int imgHeight = sourceImg.getHeight();//图片高int imgWidth = sourceImg.getWidth();//图片宽if (Math.abs(ruleWidth - imgWidth) <= deviation && Math.abs(ruleHeight - imgHeight) <= deviation) {gameService.updateByPrimaryKeySelective(new Game(gameId, img));msg = "上传成功!";}else {error = "图片不符合规定误!";}} catch (Exception e) {error = "文件保存本地失败!";log.error("文件保存本地失败!", e);}String res = "{ error:'" + error + "', msg:'" + msg + "',imgurl:'" + readPath + "'}";return res;}}

JSP:

<body><!-- 异步上传图片 --><b>背景图片(建议图片大小750&Chi;400,允许误差100已内)</b><br><img id="img1" alt="上传成功后显示图片" src="${fileUrl }${game.imageUrl1}"><br><input id="fileImg" type="file" name="fileImg" size="80" /><input id="saveImg" type="button" value="上传图片" /></body>

原理分析

jQuery.extend({createUploadIframe: function (id, uri) {//id为当前系统时间字符串,uri是外部传入的json对象的一个参数//create framevar frameId = 'jUploadFrame' + id; //给iframe添加一个独一无二的idvar iframeHtml = '<iframe id="' + frameId + '" name="' + frameId + '" style="position:absolute; top:-9999px; left:-9999px"'; //创建iframe元素if (window.ActiveXObject) {//判断浏览器是否支持ActiveX控件if (typeof uri == 'boolean') {iframeHtml += ' src="' + 'javascript:false' + '"';} else if (typeof uri == 'string') {iframeHtml += ' src="' + uri + '"';}}iframeHtml += ' />';jQuery(iframeHtml).appendTo(document.body); //将动态iframe追加到body中return jQuery('#' + frameId).get(0); //返回iframe对象 },createUploadForm: function (id, fileElementId, data) {//id为当前系统时间字符串,fileElementId为页面<input type='file' />的id,data的值需要根据传入json的键来决定//create form var formId = 'jUploadForm' + id; //给form添加一个独一无二的idvar fileId = 'jUploadFile' + id; //给<input type='file' />添加一个独一无二的idvar form = jQuery('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data" ></form>'); //创建form元素if (data) {//通常为falsefor (var i in data) {jQuery('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendTo(form); //根据data的内容,创建隐藏域,这部分我还不知道是什么时候用到。估计是传入json的时候,如果默认传一些参数的话要用到。 }} var oldElement = jQuery('#' + fileElementId); //得到页面中的<input type='file' />对象var newElement = jQuery(oldElement).clone(); //克隆页面中的<input type='file' />对象jQuery(oldElement).attr('id', fileId); //修改原对象的idjQuery(oldElement).before(newElement); //在原对象前插入克隆对象jQuery(oldElement).appendTo(form); //把原对象插入到动态form的结尾处//set attributesjQuery(form).css('position', 'absolute'); //给动态form添加样式,使其浮动起来,jQuery(form).css('top', '-1200px');jQuery(form).css('left', '-1200px');jQuery(form).appendTo('body'); //把动态form插入到body中return form;},ajaxFileUpload: function (s) {//这里s是个json对象,传入一些ajax的参数// TODO introduce global settings, allowing the client to modify them for all requests, not only timeout s = jQuery.extend({}, jQuery.ajaxSettings, s); //此时的s对象是由jQuery.ajaxSettings和原s对象扩展后的对象var id = new Date().getTime(); //取当前系统时间,目的是得到一个独一无二的数字var form = jQuery.createUploadForm(id, s.fileElementId, (typeof (s.data) == 'undefined' ? false : s.data)); //创建动态formvar io = jQuery.createUploadIframe(id, s.secureuri); //创建动态iframevar frameId = 'jUploadFrame' + id; //动态iframe的idvar formId = 'jUploadForm' + id; //动态form的id// Watch for a new set of requestsif (s.global && !jQuery.active++) {//当jQuery开始一个ajax请求时发生jQuery.event.trigger("ajaxStart"); //触发ajaxStart方法} var requestDone = false; //请求完成标志// Create the request objectvar xml = {}; if (s.global)jQuery.event.trigger("ajaxSend", [xml, s]); //触发ajaxSend方法// Wait for a response to come backvar uploadCallback = function (isTimeout) {//回调函数var io = document.getElementById(frameId); //得到iframe对象try {if (io.contentWindow) {//动态iframe所在窗口对象是否存在xml.responseText = io.contentWindow.document.body ? io.contentWindow.document.body.innerHTML : null;xml.responseXML = io.contentWindow.document.XMLDocument ? io.contentWindow.document.XMLDocument : io.contentWindow.document;} else if (io.contentDocument) {//动态iframe的文档对象是否存在xml.responseText = io.contentDocument.document.body ? io.contentDocument.document.body.innerHTML : null;xml.responseXML = io.contentDocument.document.XMLDocument ? io.contentDocument.document.XMLDocument : io.contentDocument.document;}} catch (e) {jQuery.handleError(s, xml, null, e);} if (xml || isTimeout == "timeout") {//xml变量被赋值或者isTimeout == "timeout"都表示请求发出,并且有响应requestDone = true; //请求完成var status;try {status = isTimeout != "timeout" ? "success" : "error"; //如果不是“超时”,表示请求成功// Make sure that the request was successful or notmodifiedif (status != "error") { // process the data (runs the xml through httpData regardless of callback)var data = jQuery.uploadHttpData(xml, s.dataType); //根据传送的type类型,返回json对象,此时返回的data就是后台操作后的返回结果// If a local callback was specified, fire it and pass it the dataif (s.success)s.success(data, status); //执行上传成功的操作// Fire the global callbackif (s.global)jQuery.event.trigger("ajaxSuccess", [xml, s]);} elsejQuery.handleError(s, xml, status);} catch (e) {status = "error";jQuery.handleError(s, xml, status, e);}// The request was completedif (s.global)jQuery.event.trigger("ajaxComplete", [xml, s]);// Handle the global AJAX counterif (s.global && ! --jQuery.active)jQuery.event.trigger("ajaxStop");// Process resultif (plete)plete(xml, status);jQuery(io).unbind();//移除iframe的事件处理程序setTimeout(function () {//设置超时时间try {jQuery(io).remove();//移除动态iframejQuery(form).remove();//移除动态form} catch (e) {jQuery.handleError(s, xml, null, e);}}, 100)xml = null}} // Timeout checkerif (s.timeout > 0) {//超时检测setTimeout(function () {// Check to see if the request is still happeningif (!requestDone) uploadCallback("timeout");//如果请求仍未完成,就发送超时信号 }, s.timeout);} try { var form = jQuery('#' + formId);jQuery(form).attr('action', s.url);//传入的ajax页面导向urljQuery(form).attr('method', 'POST');//设置提交表单方式jQuery(form).attr('target', frameId);//返回的目标iframe,就是创建的动态iframeif (form.encoding) {//选择编码方式jQuery(form).attr('encoding', 'multipart/form-data');} else {jQuery(form).attr('enctype', 'multipart/form-data');}jQuery(form).submit();//提交form表单} catch (e) {jQuery.handleError(s, xml, null, e);}jQuery('#' + frameId).load(uploadCallback); //ajax 请求从服务器加载数据,同时传入回调函数return { abort: function () { } };},uploadHttpData: function (r, type) { var data = !type;data = type == "xml" || data ? r.responseXML : r.responseText; // If the type is "script", eval it in global contextif (type == "script")jQuery.globalEval(data); // Get the JavaScript object, if JSON is used.if (type == "json")eval("data = " + data); // evaluate scripts within htmlif (type == "html")jQuery("<div>").html(data).evalScripts(); return data;}})

ajaxfileupload.js

$.ajaxFileUpload({url: '../../XXXX/XXXX.aspx', //用于文件上传的服务器端请求地址secureuri: false, //一般设置为falsefileElementId: $("input#xxx").attr("id"), //文件上传控件的id属性 <input type="file" id="file" name="file" /> 注意,这里一定要有name值 //$("form").serialize(),表单序列化。指把所有元素的ID,NAME 等全部发过去dataType: 'json',//返回值类型 一般设置为jsoncomplete: function () {//只要完成即执行,最后执行 },success: function (data, status) //服务器成功响应处理函数{ if (typeof (data.error) != 'undefined') {if (data.error != '') {if (data.error == "1001") {//这个error(错误码)是由自己定义的,根据后台返回的json对象的键值而判断}else if (data.error == "1002") {}alert(data.msg);//同errorreturn;} else {alert(data.msg);}} /** 这里就是做一些其他操作,比如把图片显示到某控件中去之类的。*/},error: function (data, status, e)//服务器响应失败处理函数 {alert(e);}})

$.ajaxFileUpload([options])

本文章参考:逆心、超级谷歌

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。