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. viewController的自动扩展属性导致TableViewGroupStyle时向上填充

    self.automaticallyAdjustsScrollViewInsets = NO; 需设置这个属性

  2. 登陆sqlserver及修改端口号 (转)

    在一台计算机上面同时安装两个sql server数据库实例,第一次安装默认为机器名,端口号为1433 1.如果不知道服务器名,却想登陆的话可以直接输入127.0.0.1登陆之后,在新建查询中输入:SE ...

  3. javaweb-dbutils

    package cn.itcast.demo; import java.io.File;import java.io.FileNotFoundException;import java.io.File ...

  4. windows socket网络编程基础知识

    下面介绍网络7层协议在WINDOWS的实现: 7层协议 WIN系统 ________________________________________ 7 应用层 7 应用程序 ____________ ...

  5. Bash简介

    Bash(GNU bourne-Again Shell)是一个为GNU计划编写的Unix shell,它是很多Linux平台默认的使用的shell. shell是一个命令解析器,是介于操作系统内核与用 ...

  6. Mac快捷键 Xcode快捷键

    Mac OSX 快捷键&命令行   一.Mac OSX 快捷键 ctrl+shift                                    快速放大dock的图标会暂时放大,而 ...

  7. iptables_forward

    FORWARD 好了,我们接着往下走,这个包已经过了两个PREROUTING链了,这个时候,出现了一个分支转折的地方,也就是图中下方的那个菱形(FORWARD),转发!这里有一个对目的地址的判断(这里 ...

  8. PHP 防范xss攻击

    XSS 全称为 Cross Site Scripting,用户在表单中有意或无意输入一些恶意字符,从而破坏页面的表现! 看看常见的恶意字符XSS 输入: 1.XSS 输入通常包含 JavaScript ...

  9. WCF之服务说明

    实质:服务说明实质上就是服务相关的一些信息. 1.服务端代码添加了如下黄色代码: class Program { static void Main(string[] args) { //创建一个Ser ...

  10. JQuery事件手册

    blur.focus     blur失去焦点:focus获得焦点 load 当指定的元素(及子元素)已加载时,会发生 load() 事件 resize 当调整浏览器窗口的大小时,发生 resize ...