GVKun编程网logo

ajaxFileUpload插件的使用 ------------------插件(ajaxfileupload用法)

12

以上就是给各位分享ajaxFileUpload插件的使用------------------插件,其中也会对ajaxfileupload用法进行解释,同时本文还将给你拓展$.ajaxFileUploa

以上就是给各位分享ajaxFileUpload插件的使用 ------------------插件,其中也会对ajaxfileupload用法进行解释,同时本文还将给你拓展$.ajaxFileUpload is not a function,使用ajaxfileupload.js时提交报错、ajaxFileUpload.js 插件上传图片遇到的坑、ajaxFileUpload.js 插件的demo、ajaxfileupload.js 文件上传插件之改进等相关知识,如果能碰巧解决你现在面临的问题,别忘了关注本站,现在开始吧!

本文目录一览:

ajaxFileUpload插件的使用 ------------------插件(ajaxfileupload用法)

ajaxFileUpload插件的使用 ------------------插件(ajaxfileupload用法)

这个插件只能上传,不能判断文件大小,类型,要自己写js判断,或后台判断

http://www.phpletter.com/Our-Projects/AjaxFileUpload/

可以直接对DEMO进行修改就行

下面是一个函数:

//ajax上传头像图片
function ajaxFileUpload() {
var filePath = $("#filetoUpload").val();
if (!filePath || filePath == "" || filePath == null) {
$("#filetoUploadMsg").html("").html("<font color='Red'>请选择一个上传的图片</font>");
return false;
}
//显示和隐藏加载图片
$("#loading").ajaxStart(function () {
$(this).show();
})

.ajaxComplete(function () {
$(this).hide();
});

//ajax上传头像图片
$.ajaxFileUpload
(
{
url: '/User/Upload',
secureuri: false,
fileElementId: 'filetoUpload',
dataType: 'json',//这个是后台返回的数据类型,可以是json,text,html,script
success: function (data,status) {
var error = data.err;
var filepath = data.msg;
if (error != "") {
asyncBox.tips(error,'error');//异步盒子插件的提示
} else {
$("#viewImage").attr("src",filepath);
$("#settingLeftimage").attr("src",filepath);
asyncBox.tips('上传头像成功 !','success');
}
},
error: function (data,status,e) {
asyncBox.tips(e,'error');
}
}
)
return false;
}

下面是下载的一个文件,(别人写的)

jQuery插件AjaxFileUpload可以实现ajax文件上传

jQuery插件AjaxFileUpload可以实现ajax文件上传,该插件使用非常简单,首先了解一下正确使用AjaxFileUpload插件的方法,然后再了解一些常见的错误信息和解决方法。

使用说明

需要使用jQuery库文件 和AjaxFileUpload库文件

使用实例

http://www.phpletter.com/contents/ajaxfileupload/ajaxfileupload.js

一,包含文件部分

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="ajaxfileupload.js"></script>

二,HTML部分

<img id="loading " src="loading.gif"https://www.jb51.cc/tag/dis/" target="_blank">display:none;">
<input id="filetoUpload " type="file" size="20" name="filetoUpload ">
<buttonid="buttonUpload" onclick="return ajaxFileUpload ();">上传</button>

只需要三个元素,一个动态加载小图标、一个文件域和一个按钮
注意:使用AjaxFileUpload插件上传文件可不需要form,如下:

<form name="form" action="" method="POST" enctype="multipart/form-data">
……相关HTML代码……
</form>

因为AjaxFileUpload插件会自动生成一个form提交表单。

对于file文件域ID和name,ajaxFileUpload插件fileElementId参数需要获取文件域ID,如果处理上传文件操作就需要知道文件域name,以便获取上传文件信息,这两者关系一定要清楚。

三,javascript部分

<script type="text/javascript">
function ajaxFileUpload (){
loading();//动态加载小图标
$.ajaxFileUpload ({
url :'upload.PHP',
secureuri :false,
fileElementId :'filetoUpload',
dataType : 'json',
success : function (data,status){
if(typeof(data.error) != 'undefined'){
if(data.error != ''){
alert(data.error);
}else{
alert(data.msg);
}
}
},e){
alert(e);
}
})
return false;
}
function loading (){
$("#loading ").ajaxStart(function(){
$(this).show();
}).ajaxComplete(function(){
$(this).hide();
});
}
</script>

主要参数说明:
1,url表示处理文件上传操作的文件路径,可以测试URL是否能在浏览器中直接访问,如上:upload.PHP
2,fileElementId表示文件域ID,如上:filetoUpload
3,secureuri是否启用安全提交,默认为false
4,dataType数据数据,一般选json,javascript的原生态
5,success提交成功后处理函数
6,error提交失败处理函数

上面有两个方法,一个动态加载小图标提示函数loading()和ajaxFileUpload文件上传$.ajaxFileUpload()函数,这与我们使用jQuery.ajax()函数差不多,使用很简单,
这里我省略了PHP处理上传文件,使用jQuery插件 AjaxFileUpload实现ajax文件就这么简单。

同时我们需要了解相关的错误提示

1,SyntaxError: missing ; before statement错误
如果出现这个错误就需要检查url路径是否可以访问

2,SyntaxError: Syntax error错误
如果出现这个错误就需要检查处理提交操作的PHP文件是否存在语法错误

3,SyntaxError: invalid property id错误
如果出现这个错误就需要检查属性ID是否存在

4,SyntaxError: missing } in XML expression错误
如果出现这个错误就需要检查文件域名称是否一致或不存在

5,其它自定义错误
大家可使用变量$error直接打印的方法检查各参数是否正确,比起上面这些无效的错误提示还是方便很多。

使用jQuery插件AjaxFileUpload实现无刷新上传文件非常实用,由于其简单易用,因些这个插件相比其它文件上传插件使用人数最多,非常值得推荐。

处理页面:

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

public partial class web_ajax_FileUpload : System.Web.UI.Page
{
protected void Page_Load(object sender,EventArgs e)
{
HttpFileCollection files = HttpContext.Current.Request.Files;


//if (files[0].ContentLength > 5)
//{
// Response.Write("{");
// Response.Write("msg:'" + files[0].FileName + "',");
// Response.Write("error:'文件上传失败'");
// Response.Write("}");
//}
//else
//{
// Response.Write("{");
// Response.Write("msg:'没有文件被上传',");
// Response.Write("error:'文件上传失败'");
// Response.Write("}");
//}
files[0].SaveAs("d:/adw.jpg");
Response.Write("{");
Response.Write("msg:'a',");
Response.Write("error:''");
Response.Write("}");

//Response.Write("{"); //Response.Write("msg:'ggg\n',"); //Response.Write("error:'aa\n'"); //Response.Write("}"); Response.End(); } }

$.ajaxFileUpload is not a function,使用ajaxfileupload.js时提交报错

$.ajaxFileUpload is not a function,使用ajaxfileupload.js时提交报错

$.ajaxFileUpload is not a function,使用ajaxfileupload.js时提交报错,这是什么原因?

ajaxFileUpload.js 插件上传图片遇到的坑

ajaxFileUpload.js 插件上传图片遇到的坑

用 ajaxFileUpload 上传图触发一次change事件后,下次就不会再触发change事件 ,必须要刷新页面才可以再次上传
修改前的写法:
$(''#uploadFile'').change(function () {
            var f = document.getElementById(''uploadFile'').files[0]
            if (f.size > 2 * 1024 * 1024) {
                dialogMsg("文件过大, 建议文件小于2M", -1);
                return;
            }
            var src = window.URL.createObjectURL(f);
            document.getElementById(''uploadPreview'').src = src;

            //上传应用图标
            $.ajaxFileUpload({
                url: "/Member/UploadFile",
                secureuri: false,
                fileElementId: ''uploadFile'',
                dataType: ''json'',
                success: function (data) {
                    $("#up_license").val(data.resultdata.path);
                    dialogMsg(data.message, 1);
                 
                }
            });
        });

第一次可以上传,第二次重新上传没有触发,原因是由于ajaxFileUpload把原来的file元素替换成新的file元素,导致change事件失效

网上说将ajaxFileUpload源码为jQuery(oldElement).clone())改为$(oldElement).clone(true) 这样可以在复制元素的同时复制事件 然而处理后并没有起作用。

有人说重新绑定change事件,于是:

修改后的写法:

$(''#uploadFile'').change(function () {
            UploadImg();
        });
        UploadImg = function () {
            var f = document.getElementById(''uploadFile'').files[0]
            if (f.size > 2 * 1024 * 1024) {
                dialogMsg("文件过大, 建议文件小于2M", -1);
                return;
            }
            var src = window.URL.createObjectURL(f);
            document.getElementById(''uploadPreview'').src = src;

            //上传应用图标
            $.ajaxFileUpload({
                url: "/Member/UploadFile",
                secureuri: false,
                fileElementId: ''uploadFile'',
                dataType: ''json'',
                success: function (data) {
                    $("#up_license").val(data.resultdata.path);
                    dialogMsg(data.message, 1);
                    $(''#uploadFile'').change(function () { //重新绑定事件
                        UploadImg();
                    });
                }
            });
        }

在回调函数里 重新绑定change事件,这样就change事件失效的问题就解决了,亲测,有效!!

ajaxFileUpload.js 插件的demo

ajaxFileUpload.js 插件的demo

依赖js文件:

<!-- jQuery 核心文件 -->
    <script src="../3rd/jquery/dist/jquery.js"></script>
<!-- ajaxFileUpload上传插件 -->
    <script src="../3rd/ajaxfileupload/ajaxfileupload.js" type="text/javascript"></script>

HTML代码:

<!-- ajaxFileUpload的上传功能 -->
        <div>
            <div>
                <label for="file1">安装包上传</label>
                <inputtype="file" id="file1" name="file" /><br />
            </div>
        </div>

js代码:
/* 上传安装包:ajax上传插件使用 */
function ajaxFileUploadd() {
    $.ajaxFileUpload
    (
        {
            url: '/upgrade-release/rpc?method=/proHandRelea/uploadSetupPack',//用于文件上传的服务器端请求地址
            secureuri: false,//是否需要安全协议,一般设置为false
            fileElementId: 'file1',//文件上传域的ID
            dataType: 'json',//返回值类型 一般设置为json
            type: 'post',success: function(data,status)  //服务器成功响应处理函数
            {
                var dataJson = jQuery.parseJSON(data);
                if(status == 'success') {
                    // 上传成功
                    if(dataJson.resultMsg == 1) {
                        // 3、基本信息保存
                        submitBasicMsg();
                    }
                    if(dataJson.resultMsg == 0) { // 上传失败
                        doFalAlert("上传文件失败,发布失败!请重新上传文件再发布!");
                    }
                }
            },error: function (data,status,e)//服务器响应失败处理函数
            {
                // alert(e);
                doFalAlert("系统异常,上传文件路径异常!");
            }

        }
    )
    return false;
}

注意问题:

可能会出现:上传报错 jQuery.handleError is not a function这个异常

分析并解决:handlerError只在jquery-1.4.2之前的版本中存在,jquery-1.4.2之后的版本中都没有这个函数了。
因此在jquery高级版本中将这个函数添加上 ,问题解决。 以下是添加过handlerError方法的ajaxupload.js 文件,直接拿过去用即可。

jQuery.extend({
	

    createUploadIframe: function(id,uri)
	{
			//create frame
            var frameId = 'jUploadFrame' + id;
            var iframeHtml = '<iframe id="' + frameId + '" name="' + frameId + '"';
			if(window.ActiveXObject)
			{
                if(typeof uri== 'boolean'){
					iframeHtml += ' src="' + 'javascript:false' + '"';

                }
                else if(typeof uri== 'string'){
					iframeHtml += ' src="' + uri + '"';

                }	
			}
			iframeHtml += ' />';
			jQuery(iframeHtml).appendTo(document.body);

            return jQuery('#' + frameId).get(0);			
    },createUploadForm: function(id,fileElementId,data)
	{
		//create form	
		var formId = 'jUploadForm' + id;
		var fileId = 'jUploadFile' + id;
		var form = jQuery('<form  action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');	
		if(data)
		{
			for(var i in data)
			{
				jQuery('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendTo(form);
			}			
		}		
		var oldElement = jQuery('#' + fileElementId);
		var newElement = jQuery(oldElement).clone();
		jQuery(oldElement).attr('id',fileId);
		jQuery(oldElement).before(newElement);
		jQuery(oldElement).appendTo(form);


		
		//set attributes
		jQuery(form).css('position','absolute');
		jQuery(form).css('top','-1200px');
		jQuery(form).css('left','-1200px');
		jQuery(form).appendTo('body');		
		return form;
    },handleError: function( s,xhr,e ) 		{
    	// If a local callback was specified,fire it
    			if ( s.error ) {
    				s.error.call( s.context || s,e );
    			}

    			// Fire the global callback
    			if ( s.global ) {
    				(s.context ? jQuery(s.context) : jQuery.event).trigger( "ajaxError",[xhr,s,e] );
    			}
    },ajaxFileUpload: function(s) {
        // Todo introduce global settings,allowing the client to modify them for all requests,not only timeout		
        s = jQuery.extend({},jQuery.ajaxSettings,s);
        var id = new Date().getTime()        
		var form = jQuery.createUploadForm(id,s.fileElementId,(typeof(s.data)=='undefined'?false:s.data));
		var io = jQuery.createUploadIframe(id,s.secureuri);
		var frameId = 'jUploadFrame' + id;
		var formId = 'jUploadForm' + id;		
        // Watch for a new set of requests
        if ( s.global && ! jQuery.active++ )
		{
			jQuery.event.trigger( "ajaxStart" );
		}            
        var requestDone = false;
        // Create the request object
        var xml = {}   
        if ( s.global )
            jQuery.event.trigger("ajaxSend",[xml,s]);
        // Wait for a response to come back
        var uploadCallback = function(isTimeout)
		{			
			var io = document.getElementById(frameId);
            try 
			{				
				if(io.contentwindow)
				{
					 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)
				{
					 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") 
			{				
                requestDone = true;
                var status;
                try {
                    status = isTimeout != "timeout" ? "success" : "error";
                    // Make sure that the request was successful or notmodified
                    if ( status != "error" )
					{
                        // process the data (runs the xml through httpData regardless of callback)
                        var data = jQuery.uploadHttpData( xml,s.dataType );    
                        // If a local callback was specified,fire it and pass it the data
                        if ( s.success )
                            s.success( data,status );
    
                        // Fire the global callback
                        if( s.global )
                            jQuery.event.trigger( "ajaxSuccess",s] );
                    } else
                        jQuery.handleError(s,status);
                } catch(e) 
				{
                    status = "error";
                    jQuery.handleError(s,e);
                }

                // The request was completed
                if( s.global )
                    jQuery.event.trigger( "ajaxComplete",s] );

                // Handle the global AJAX counter
                if ( s.global && ! --jQuery.active )
                    jQuery.event.trigger( "ajaxStop" );

                // Process result
                if ( s.complete )
                    s.complete(xml,status);

                jQuery(io).unbind()

                setTimeout(function()
									{	try 
										{
											jQuery(io).remove();
											jQuery(form).remove();	
											
										} catch(e) 
										{
											jQuery.handleError(s,e);
										}									

									},100)

                xml = null

            }
        }
        // Timeout checker
        if ( s.timeout > 0 ) 
		{
            setTimeout(function(){
                // Check to see if the request is still happening
                if( !requestDone ) uploadCallback( "timeout" );
            },s.timeout);
        }
        try 
		{

			var form = jQuery('#' + formId);
			jQuery(form).attr('action',s.url);
			jQuery(form).attr('method','POST');
			jQuery(form).attr('target',frameId);
            if(form.encoding)
			{
				jQuery(form).attr('encoding','multipart/form-data');      			
            }
            else
			{	
				jQuery(form).attr('enctype','multipart/form-data');			
            }			
            jQuery(form).submit();

        } catch(e) 
		{			
            jQuery.handleError(s,e);
        }
		
		jQuery('#' + frameId).load(uploadCallback	);
        return {abort: function () {}};	

    },uploadHttpData: function( r,type ) {
        var data = !type;
        data = type == "xml" || data ? r.responseXML : r.responseText;
        data = data.replace("<pre>","");
        data = data.replace("</pre>","");
        // If the type is "script",eval it in global context
        if ( type == "script" )
            jQuery.globalEval( data );
        // Get the JavaScript object,if JSON is used.
        if ( type == "json" ){
        	data = r.responseText;  
            var start = data.indexOf(">");  
            if(start != -1) {  
              var end = data.indexOf("<",start + 1);  
              if(end != -1) {  
                data = data.substring(start + 1,end);  
               }  
            } 
            eval( "data = " + data );
        }
        // evaluate scripts within html
        if ( type == "html" )
            jQuery("<div>").html(data).evalScripts();
        return data;
    }
})

ajaxfileupload.js 文件上传插件之改进

ajaxfileupload.js 文件上传插件之改进

最近做了个小项目要用到文件上传操作,上网搜到了ajaxfileupload插件,根据http://blog.csdn.net/anialy/article/details/8587837 的介绍基本能完成上传操作,但是还存在几个问题:

1. 不能批量上传,只能选择一个文件

2. 返回json格式数据不能很好处理,callback函数不能执行


解决方法:

在解决第一点时,发现ajaxfileupload.js代码中并不能体现它支不支持多文件批量上传,有人说它支持也有人说不支持。但是想想好多网站上传文件时调用的file dialog都是系统的,都能选择多文件,而且我后台代码也都是支持多文件上传的,如果只从代码中找问题可能不行。后来终于找到,在html5中有个关键字可以让dialog选择多文件,在

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

里加一个multiple即可一次性选择多个文件,Ajaxfileupload完全支持

<input type="file" id="file" name="file" multiple></input>

第二点就比较麻烦了,网上也有相关的解决办法

在Ajaxfileupload.js里添加一段代码

    handleError: function( s,xhr,status,e ) {
        // If a local callback was specified,fire it
        if ( s.error ) {
            s.error.call( s.context || s,e );
        }

        // Fire the global callback
        if ( s.global ) {
            (s.context ? jQuery(s.context) : jQuery.event).trigger( "ajaxError",[xhr,s,e] );
        }
    }

handleError:在jquery1.4以后就不支持了,而Ajaxfileupload还需要,所以需要手动加上。


加上之后callback是能执行了,但是确实只执行error。网上有两种解决方案都是修改uploadHttpData: function( r,type )中if ( type == "json" )中代码eval( "data = " + data );

但是不管我改成eval( "data = \'" + data + "\'");还是改成eval( "data = eval(" + data + ")");都不能解决。一个报miss ; error,一个报miss ) error。后来经调试发现,data在传输过程中会多了一串字符 <div id="xunlei_com_thunder_helper_plugin_d462f475-c18e-46be-bd10-327458d045bd"></div>,这应该是迅雷下载会自动加载到body最后的标签。没办法,谁让这个插件不能用response.setContentType("application/x-json");而只能用response.setContentType("text/html"); 呢。那就只能手动去除了,于是修改这段代码,并不再用eval,这个方法太容易出错,直接用js的JSON多好

if ( type == "json" ){
            var index = data.indexOf('<div');
            if(index > 0) data = data.substring(0,index);
            data = JSON.parse(data);
}

ok,至此,上面两个问题终于解决~~

修改后的文件下载地址 http://download.csdn.net/detail/huoqi12/8539935

今天关于ajaxFileUpload插件的使用 ------------------插件ajaxfileupload用法的介绍到此结束,谢谢您的阅读,有关$.ajaxFileUpload is not a function,使用ajaxfileupload.js时提交报错、ajaxFileUpload.js 插件上传图片遇到的坑、ajaxFileUpload.js 插件的demo、ajaxfileupload.js 文件上传插件之改进等更多相关知识的信息可以在本站进行查询。

本文标签: