jquery.ajaxfileupload.js上传插件,利用iframe提交不刷新页面功能完成。

  1. /*
  2. // jQuery Ajax File Uploader
  3. //
  4. // @author: Jordan Feldstein <jfeldstein.com>
  5. //
  6. // - Ajaxifies an individual <input type="file">
  7. // - Files are sandboxed. Doesn't matter how many, or where they are, on the page.
  8. // - Allows for extra parameters to be included with the file
  9. // - onStart callback can cancel the upload by returning false
  10. */
  11.  
  12. (function($) {
  13. $.fn.ajaxfileupload = function(options) {
  14. var settings = {
  15. params: {},
  16. action: '',
  17. onStart: function() { },
  18. onComplete: function(response) { },
  19. onCancel: function() { },
  20. validate_extensions : true,
  21. valid_extensions : ['gif','png','jpg','jpeg'],
  22. submit_button : null
  23. };
  24.  
  25. var uploading_file = false;
  26.  
  27. if ( options ) {
  28. $.extend( settings, options );
  29. }
  30.  
  31. // 'this' is a jQuery collection of one or more (hopefully)
  32. // file elements, but doesn't check for this yet
  33. return this.each(function() {
  34. var $element = $(this);
  35. // Skip elements that are already setup. May replace this
  36. // with uninit() later, to allow updating that settings
  37. if($element.data('ajaxUploader-setup') === true) return;
  38.  
  39. $element.change(function()
  40. {
  41. // since a new image was selected, reset the marker
  42. uploading_file = false;
  43.  
  44. // only update the file from here if we haven't assigned a submit button
  45. if (settings.submit_button == null)
  46. {
  47. upload_file();
  48. }
  49. });
  50.  
  51. if (settings.submit_button == null)
  52. {
  53. // do nothing
  54. } else
  55. {
  56. settings.submit_button.click(function(e)
  57. {
  58. // Prevent non-AJAXy submit
  59. e.preventDefault();
  60.  
  61. // only attempt to upload file if we're not uploading
  62. if (!uploading_file)
  63. {
  64. upload_file();
  65. }
  66. });
  67. }
  68.  
  69. var upload_file = function()
  70. {
  71. if($element.val() == '') return settings.onCancel.apply($element, [settings.params]);
  72. // make sure extension is valid
  73. var ext = $element.val().split('.').pop().toLowerCase();
  74. if(true === settings.validate_extensions && $.inArray(ext, settings.valid_extensions) == -1)
  75. {
  76. // Pass back to the user
  77. settings.onComplete.apply($element, [{status: false, message: 'The select file type is invalid. File must be ' + settings.valid_extensions.join(', ') + '.'}, settings.params]);
  78. } else
  79. {
  80. uploading_file = true;
  81.  
  82. // Creates the form, extra inputs and iframe used to
  83. // submit / upload the file
  84. wrapElement($element);
  85.  
  86. // Call user-supplied (or default) onStart(), setting
  87. // it's this context to the file DOM element
  88. var ret = settings.onStart.apply($element, [settings.params]);
  89.  
  90. // let onStart have the option to cancel the upload
  91. if(ret !== false)
  92. {
  93. $element.parent('form').submit(function(e) { e.stopPropagation(); }).submit();
  94. } else {
  95. uploading_file = false;
  96. }
  97. }
  98. };
  99.  
  100. // Mark this element as setup
  101. $element.data('ajaxUploader-setup', true);
  102.  
  103. /*
  104. // Internal handler that tries to parse the response
  105. // and clean up after ourselves.
  106. */
  107. var handleResponse = function(loadedFrame, element) {
  108. var response, responseStr = $(loadedFrame).contents().text();
  109. try {
  110. //response = $.parseJSON($.trim(responseStr));
  111. response = JSON.parse(responseStr);
  112. } catch(e) {
  113. response = responseStr;
  114. }
  115.  
  116. // Tear-down the wrapper form
  117. element.siblings().remove();
  118. element.unwrap();
  119.  
  120. uploading_file = false;
  121.  
  122. // Pass back to the user
  123. settings.onComplete.apply(element, [response, settings.params]);
  124. };
  125.  
  126. /*
  127. // Wraps element in a <form> tag, and inserts hidden inputs for each
  128. // key:value pair in settings.params so they can be sent along with
  129. // the upload. Then, creates an iframe that the whole thing is
  130. // uploaded through.
  131. */
  132. var wrapElement = function(element) {
  133. // Create an iframe to submit through, using a semi-unique ID
  134. var frame_id = 'ajaxUploader-iframe-' + Math.round(new Date().getTime() / 1000)
  135. $('body').after('<iframe width="0" height="0" style="display:none;" name="'+frame_id+'" id="'+frame_id+'"/>');
  136. $('#'+frame_id).get(0).onload = function() {
  137. handleResponse(this, element);
  138. };
  139.  
  140. // Wrap it in a form
  141. element.wrap(function() {
  142. return '<form action="' + settings.action + '" method="POST" enctype="multipart/form-data" target="'+frame_id+'" />'
  143. })
  144. // Insert <input type='hidden'>'s for each param
  145. .before(function() {
  146. var key, html = '';
  147. for(key in settings.params) {
  148. var paramVal = settings.params[key];
  149. if (typeof paramVal === 'function') {
  150. paramVal = paramVal();
  151. }
  152. html += '<input type="hidden" name="' + key + '" value="' + paramVal + '" />';
  153. }
  154. return html;
  155. });
  156. }
  157. });
  158. }
  159. })( jQuery )

  

使用方法

  1. <input type="file" id="image" name="image">
  2.  
  3. <script>
    $(document).ready(function(){
  4. $("#image").ajaxfileupload({
  5. 'action': '/admin/studentStore/uploadImage?time='+new Date().getTime(),
  6. 'onComplete': function(data) {
  7. var html ="";
  8. html += "<em class='del-img' onclick='deleteImg(this);' title='删除'></em>";
  9. html += "<img style='width:100%;height:100%;' src='"+data.filepath+"'>";
  10. var name = "img"+$.trim(index);
  11. html += "<input type='hidden' name="+name+" value='"+data.filepath+"'>";
  12. $("#img"+index).html(html);
  13. $("#image"+index).val("");
  14. $("#image"+index).parents(".form-uploadPic-file-wapper").hide();
  15. },
  16. 'onStart': function() {
  17. },
  18. 'onCancel': function() {
  19. },
  20. valid_extensions:['jpeg','png','gif','jpg']
  21. });
  22. });
  1. </script>

  

jquery.ajaxfileupload.js的更多相关文章

  1. Jquery ajaxfileupload.js结合.ashx文件实现无刷新上传

    先上几张图更直观展示一下要实现的功能,本功能主要通过Jquery ajaxfileupload.js插件结合ajaxUpFile.ashx一般应用程序处理文件实现Ajax无刷新上传功能,结合NPOI2 ...

  2. java jfinal + ajaxfileupload.js 上传

    功能上传 需求:同时上传多张图片 前端:jquery.ajaxfileupload.js 后端:jfinal upload.htm <html> <body> <div ...

  3. ajaxfileupload.js插件结合一般处理文件实现Ajax无刷新上传

    先上几张图更直观展示一下要实现的功能.本功能主要通过Jquery ajaxfileupload.js插件结合ajaxUpFile.ashx一般应用程序处理文件实现Ajax无刷新上传功能,结合NPOI2 ...

  4. 引用(ajaxfileupload.js) ajaxfileupload.js报这错jQuery.handleError is not a function

    jQuery.handleError is not a function 原因是,经测试handlerError只在jquery-1.4.2之前的版本中存在,jquery-1.6 和1.7中都没有这个 ...

  5. jQuery插件之上传文件ajaxfileupload.js源码与使用

    在网页应用中,一般会用到上传文件或者图片什么的到服务器,那么可以用ajaxfileupload.js,但是在使用ajaxfileupload.js时候,当服务器返回的json带有&符号的时候, ...

  6. jquery插件--ajaxfileupload.js上传文件原理分析

    英文注解应该是原作者写的吧~说实话,有些if判断里的东西我也没太弄明白,但是大致思路还是OK的. jQuery.extend({ createUploadIframe: function (id, u ...

  7. jQuery 关于IE9上传文件无法进入后台问题的原因及解决办法(ajaxfileupload.js第四弹)

    第四弹的诞生完全不在自己最初的计划之中,是有个网友看了先前关于<ajaxfileupload.js系列>的文章后提出的问题,由于自己一直是用chrome浏览器去测试demo,完全忽略IE浏 ...

  8. jQuery 自制上传头像插件-附带Demo实例(ajaxfileupload.js第三弹)

    这篇文章主要是对前两篇关于ajaxfileupload.js插件的文章 <ASP.NET 使用ajaxfileupload.js插件出现上传较大文件失败的解决方法(ajaxfileupload. ...

  9. jQuery 关于ajaxfileupload.js插件的逐步解析(ajaxfileupload.js第二弹)

    如果你看了上一篇<ASP.NET 使用ajaxfileupload.js插件出现上传较大文件失败的解决方法(ajaxfileupload.js第一弹)>的话,应该就知道我是逼不得已要认真学 ...

随机推荐

  1. Oracle Data Integrator 12c (12.1.2)新特性

    改进特性如下: 基于流程界面的声明式设计 在12c中,以前的接口(interface)已经改为映射(mapping),新的基于流程声明的设计方式更灵活,也更容易使用.在12c中,映射的实现是通过使用J ...

  2. UVALive 4682 XOR Sum (trie)

    题意:求一段连续的数字使得它们的异或和最大. 思路:首先利用前缀和求sum[i],这样求某段连续数字异或和最大就是求某两个j和i满足sum[i]^sum[j-1]最大,问题就变成了找两个数的异或最大. ...

  3. jQuery 关于 end() 方法的详细解释

    <ul class="first"> <li class="foo">list item 1</li> <li> ...

  4. hello iic

    刚刚终于弄出来了这个.发现自己很多问题. 一 mian函数 #include "led.h"#include "delay.h"#include "s ...

  5. redis简介以及与memcached比较

    一.redis (1)简介: Redis是一个开源的使用ANSI C语言编写.支持网络.可基于内存亦可持久化的日志型.Key-Value数据库,并提供多种语言的API.是noSql数据库的一种. re ...

  6. 认真对待每一道算法题 之 两个排序好的数组寻找的第k个大的数

    转载博客:http://www.cnblogs.com/buptLizer/archive/2012/03/31/2427579.html 题目意思:给出两个排好序的数组 ,不妨设为a,b都按升序排列 ...

  7. 封装定制的Kali Live ISO

    打造专属的Kali ISO – 简介 封装定制的Kali ISO很简单,很有趣,很有意义.你可以用Debian的live-build脚本对Kali ISO进行全面的配置.这些脚本以一系列配置文件的方式 ...

  8. 深入学习:Windows下Git入门教程(下)

    声明:由于本人对于Git的学习还处于摸索阶段,对有些概念的理解或许只是我断章取义,有曲解误导的地方还请见谅指正! 一.分支 1.1分支的概念. 对于的分支的理解,我们可以用模块化这个词来解释:在日常工 ...

  9. PHP版本区别

  10. html input

    disabled="disabled" <input name="" type="checkbox" value="&quo ...