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

/*
// jQuery Ajax File Uploader
//
// @author: Jordan Feldstein <jfeldstein.com>
//
// - Ajaxifies an individual <input type="file">
// - Files are sandboxed. Doesn't matter how many, or where they are, on the page.
// - Allows for extra parameters to be included with the file
// - onStart callback can cancel the upload by returning false
*/ (function($) {
$.fn.ajaxfileupload = function(options) {
var settings = {
params: {},
action: '',
onStart: function() { },
onComplete: function(response) { },
onCancel: function() { },
validate_extensions : true,
valid_extensions : ['gif','png','jpg','jpeg'],
submit_button : null
}; var uploading_file = false; if ( options ) {
$.extend( settings, options );
} // 'this' is a jQuery collection of one or more (hopefully)
// file elements, but doesn't check for this yet
return this.each(function() {
var $element = $(this);
// Skip elements that are already setup. May replace this
// with uninit() later, to allow updating that settings
if($element.data('ajaxUploader-setup') === true) return; $element.change(function()
{
// since a new image was selected, reset the marker
uploading_file = false; // only update the file from here if we haven't assigned a submit button
if (settings.submit_button == null)
{
upload_file();
}
}); if (settings.submit_button == null)
{
// do nothing
} else
{
settings.submit_button.click(function(e)
{
// Prevent non-AJAXy submit
e.preventDefault(); // only attempt to upload file if we're not uploading
if (!uploading_file)
{
upload_file();
}
});
} var upload_file = function()
{
if($element.val() == '') return settings.onCancel.apply($element, [settings.params]);
// make sure extension is valid
var ext = $element.val().split('.').pop().toLowerCase();
if(true === settings.validate_extensions && $.inArray(ext, settings.valid_extensions) == -1)
{
// Pass back to the user
settings.onComplete.apply($element, [{status: false, message: 'The select file type is invalid. File must be ' + settings.valid_extensions.join(', ') + '.'}, settings.params]);
} else
{
uploading_file = true; // Creates the form, extra inputs and iframe used to
// submit / upload the file
wrapElement($element); // Call user-supplied (or default) onStart(), setting
// it's this context to the file DOM element
var ret = settings.onStart.apply($element, [settings.params]); // let onStart have the option to cancel the upload
if(ret !== false)
{
$element.parent('form').submit(function(e) { e.stopPropagation(); }).submit();
} else {
uploading_file = false;
}
}
}; // Mark this element as setup
$element.data('ajaxUploader-setup', true); /*
// Internal handler that tries to parse the response
// and clean up after ourselves.
*/
var handleResponse = function(loadedFrame, element) {
var response, responseStr = $(loadedFrame).contents().text();
try {
//response = $.parseJSON($.trim(responseStr));
response = JSON.parse(responseStr);
} catch(e) {
response = responseStr;
} // Tear-down the wrapper form
element.siblings().remove();
element.unwrap(); uploading_file = false; // Pass back to the user
settings.onComplete.apply(element, [response, settings.params]);
}; /*
// Wraps element in a <form> tag, and inserts hidden inputs for each
// key:value pair in settings.params so they can be sent along with
// the upload. Then, creates an iframe that the whole thing is
// uploaded through.
*/
var wrapElement = function(element) {
// Create an iframe to submit through, using a semi-unique ID
var frame_id = 'ajaxUploader-iframe-' + Math.round(new Date().getTime() / 1000)
$('body').after('<iframe width="0" height="0" style="display:none;" name="'+frame_id+'" id="'+frame_id+'"/>');
$('#'+frame_id).get(0).onload = function() {
handleResponse(this, element);
}; // Wrap it in a form
element.wrap(function() {
return '<form action="' + settings.action + '" method="POST" enctype="multipart/form-data" target="'+frame_id+'" />'
})
// Insert <input type='hidden'>'s for each param
.before(function() {
var key, html = '';
for(key in settings.params) {
var paramVal = settings.params[key];
if (typeof paramVal === 'function') {
paramVal = paramVal();
}
html += '<input type="hidden" name="' + key + '" value="' + paramVal + '" />';
}
return html;
});
}
});
}
})( jQuery )

  

使用方法

<input type="file" id="image" name="image">

<script>
$(document).ready(function(){
$("#image").ajaxfileupload({
'action': '/admin/studentStore/uploadImage?time='+new Date().getTime(),
'onComplete': function(data) {
var html ="";
html += "<em class='del-img' onclick='deleteImg(this);' title='删除'></em>";
html += "<img style='width:100%;height:100%;' src='"+data.filepath+"'>";
var name = "img"+$.trim(index);
html += "<input type='hidden' name="+name+" value='"+data.filepath+"'>";
$("#img"+index).html(html);
$("#image"+index).val("");
$("#image"+index).parents(".form-uploadPic-file-wapper").hide();
},
'onStart': function() {
},
'onCancel': function() {
},
valid_extensions:['jpeg','png','gif','jpg']
});
});
</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. Struts2 的ModelDriven理解

    以UserAction为例,当UserAction实现了ModelDriven接口之后,与该接口相关的默认配置的拦截器会在拦截请求之后判断该请求是将要被UserAction处理而且UserAction ...

  2. Ubuntu 14.10 下Ganglia监控Hadoop集群

    前提是已经安装好Ganglia和Hadoop集群 1 Master节点配置hadoop-metrics2.properties # syntax: [prefix].[source|sink|jmx] ...

  3. Note_Master-Detail Application(iOS template)_04_ YJYMasterViewController.h

    //YJYMasterViewController.h #import <UIKit/UIKit.h> @classYJYDetailViewController; #import < ...

  4. hdu 2080

    ps:水题...求夹角...先求出COS,然后用acos 代码: #include "stdio.h" #include "math.h" int main() ...

  5. 看了这篇文章,Java编程速度我都惊呆了

    熟记于心,打遍天下,(开始装了) 保存 Ctrl+s                    (这个就不用解释了吧!!!!) 注释代码 Ctrl+/ 取消注释 Ctrl+/代码辅助 Alt+/ 快速修复 ...

  6. DirectX 文本绘制

    在Direct中进行文本绘制,可以通过Win32程序框架实现,也可以通过DXUT进行绘制. 基于第一篇的Win32框架入门实现非常简单,只需要添加数行代码即可.主要说需要修改的地方. #pragma  ...

  7. 我的第一个unity3d Shader, 很简单,基本就是拷贝

    Shader "Castle/ColorMix" { Properties { // 基本贴图 _MainTex ("Texture Image", 2D) = ...

  8. oracle将多条数据合并成一条

    select  t.col1,t.col2  ,wmsys.wm_concat(t.col3||' ') AS col3 , wmsys.wm_concat(t.col4||'') as col4,w ...

  9. 解析nginx负载均衡

    原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 .作者信息和本声明.否则将追究法律责任.http://baidutech.blog.51cto.com/4114344/1033718 ...

  10. jquery ui tab标签

    <!DOCTYPE html> <html> <head> <title>tab</title> <style type=" ...