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. IntelliJ IDEA 12.0

    User name:JavaDeveloper Serial number:92547-KY2BB-QZ0S1-PEZCV-HUT8Q-6RYY4

  2. treap模版代码

    treap模版暂存. 以后修改整理. #include<cstdio> #include<iostream> #include <time.h> #include& ...

  3. objectARX 获取ucs的X方向

    struct resbuf var; acedGetVar(_T("UCSXDIR"), &var);//获取用户坐标系下X方向量 ver = asVec3d(var.re ...

  4. html5 placeholder

    placeholder是html5<input>标签的一个属性,placeholder 属性提供可描述输入字段预期值的提示信息(hint).该提示会在输入字段为空时显示,并会在字段获得焦点 ...

  5. C++语法疑点

    1函数模板不支持偏特化 2类内部的typedef 必须放在最前面,不然没法用: 疑问:为什么类声明处定义的函数体中能出现在后面在声明的成员变量??因为C++对于成员函数函数体的解析是放在整个类声明完毕 ...

  6. 使用树莓派和kali Linux打造便携式渗透套件

    在DIY前你需要: .树莓派Raspberry Pi Model B+型 或者 树莓派2代; .充电宝 X1; .USB WIFI网卡 X1; .8G SD卡 X1; .Raspberry PI触摸显 ...

  7. Interview----判断整数序列是否是二叉搜索树的后序遍历结果

    题目:输入一个整数数组,判断该数组是不是某二元查找树的后序遍历的结果. 如果是返回true,否则返回false. 例如输入5.7.6.9.11.10.8,由于这一整数序列是如下树的后序遍历结果:   ...

  8. [Camel Basics]

    Define routes: Either using Spring xml or Java DSL. Spring xml: <camelContext> <routeBuilde ...

  9. C#判断字符串是否为数字

    string i = Console.ReadLine();            int a=0;            if (int.TryParse(i, out a) == false) / ...

  10. 阅读<构建之法>第13、14、15、16、17章 与 《一个程序员的生命周期》读后感

    第十三章   软件测试 这一章介绍了很多关于测试的方法,比如说单元测试,代码覆盖率测试,构建验证测试,验收测试等,我有一个很纠结的问题,如果我开发软件,是把这么多测试全做完,还是挑一些测试来进行呢?如 ...