阿贾克斯文件上传不工作的IE8斯文、上传、工作、阿贾克

2023-09-11 22:32:43 作者:西紅柿炒番茄

我无法上传使用JavaScript函数,使一个Ajax调用一个servlet的文件。该文件是完全上传时,我使用Chrome,而不是当我使用IE8(去图)。

我曾经对我的窗体底部的文件选择按钮。当我点击该按钮功能将被调用,它将使用AJAX的文件上传到该servlet。这在IE8的工作完美,但客户想链接,而不是。所以现在我有形式隐藏与CSS的按钮中的链接,和。该链接调用按钮的点击事件。现在,该文件只上传Chrome浏览器的工作原理,而不是IE8。

请求从不给该servlet出于某种原因,出于某种原因,Ajax请求返回成功。任何想法是什么问题呢?

下面是我的code:

  //上传文件
    $(#uploaded_file)。改变(函数(){
        变种文件名= $(本).VAL();
        如果(isAcceptable(文件名)){
            $ .ajaxFileUpload
            (
                {
                    键入:POST,
                    网址:GenerateServlet,
                    secureuri:假的,
                    fileElementId:uploaded_file,
                    数据类型:JSON,
                    成功:功能(数据,状态)
                    {
                        如果(typeof运算(data.error)!=未定义)
                        {
                            如果(data.error!='')
                            {
                                警报(data.error);
                            }其他
                            {
                                警报(data.msg);
                            }
                        }
                        fillTemplate(数据);

                    }
                }
            )
        }
        否则如果(filename.length大于0){
            $(#uploaded_file)VAL()。
            警报(无效的文件!请选择其他文件)
        }
    });

$(#upload_link)。点击(函数(){
        。的document.getElementById('uploaded_file')点击();
        返回false;
    });
 

下面是上传功能:

  jQuery.extend({


    createUploadIframe:功能(ID,URI)
    {
            //创建框架
            VAR frameId ='jUploadFrame'+ ID;
            VAR iframeHtml ='< IFRAME ID =+ frameId +'NAME =+ frameId +'的风格=的位置是:绝对的;顶部:-9999px;左:-9999px';
            如果(window.ActiveXObject)
            {
                如果(typeof运算URI =='布尔'){
                    iframeHtml + ='SRC =+的javascript:假'+'';

                }
                否则,如果(typeof运算URI =='串'){
                    iframeHtml + ='SRC =+ URI +';

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

            返回的jQuery(#+ frameId)获得(0);
    },
    createUploadForm:功能(ID,fileElementId,数据)
    {
        //创建窗体
        VAR formId ='jUploadForm'+ ID;
        VAR FILEID ='jUploadFile'+ ID;
        VAR形式=的jQuery('<形式的行动=的方法=POSTNAME =+ formId +'ID =+ formId +'ENCTYPE =的multipart / form-data的>< /形式GT;');
        如果(数据)
        {
            对于(数据变种I)
            {
                jQuery的('<输入类型=隐藏名称=+ I +'值=+数据[I] +'/>').appendTo(form);
            }
        }
        VAR oldElement =的jQuery(#+ fileElementId);
        VAR为newElement =的jQuery(oldElement).clone();
        jQuery的(oldElement).attr('身份证',FILEID);
        jQuery的(oldElement)。之前(为newElement);
        jQuery的(oldElement).appendTo(形式);



        //属性集
        jQuery的(形式)的CSS('位置','绝对');
        jQuery的(形式)的CSS('顶','-1200px');
        jQuery的(形式)的CSS(左,-1200px');
        jQuery的(形式).appendTo(身体);
        返回的形式;
    },

    ajaxFileUpload:功能(多个){
        // TODO引入全局设置,允许客户端修改它们的所有请求,不仅超时
        S = jQuery.extend({},jQuery.ajaxSettings,多个);
        VAR ID =新的日期()。的getTime()
        VAR形式= jQuery.createUploadForm(ID,s.fileElementId,(typeof运算(s.data)==未定义错误:s.data));
        CONSOLE.LOG(表);
        变种io的= jQuery.createUploadIframe(ID,s.secureuri);
        VAR frameId ='jUploadFrame'+ ID;
        VAR formId ='jUploadForm'+ ID;
        //看一套新的请求
        如果(s.global&安培;&安培;!jQuery.active ++)
        {
            jQuery.event.trigger(ajaxStart);
        }
        VAR requestDone = FALSE;
        //创建请求对象
        VAR XML = {}
        如果(s.global)
            jQuery.event.trigger(ajaxSend,[XML,S]);
        //等待响应回来
        VAR uploadCallback =功能(isTimeout)
        {
            VAR IO =的document.getElementById(frameId);
            尝试
            {
                如果(io.contentWindow)
                {
                     ?xml.responseText = io.contentWindow.document.body io.contentWindow.document.body.innerHTML:空;
                     xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;

                }否则,如果(io.contentDocument)
                {
                     ?xml.responseText = io.contentDocument.document.body io.contentDocument.document.body.innerHTML:空;
                    xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document;
                }
            }赶上(五)
            {
                jQuery.handleError(S,XML,空,E);
            }
            如果(XML || isTimeout ==超时)
            {
                requestDone = TRUE;
                VAR状态;
                尝试 {
                    状态= isTimeout!=超时? 成功:错误;
                    //确保请求成功或notmodified
                    如果(状态!=错误)
                    {
                        //处理数据(贯穿httpData的XML不管回调)
                        VAR数据= jQuery.uploadHttpData(XML,s.dataType);
                        //如果指定了当地的回调,火,并把它传递数据
                        如果(s.success)
                            s.success(数据,状态);

                        //火全局回调
                        如果(s.global)
                            jQuery.event.trigger(的ajaxSuccess,[XML,S]);
                    } 其他
                        jQuery.handleError(S,XML,地位);
                }赶上(五)
                {
                    状态=错误;
                    jQuery.handleError(S,XML,地位,E);
                }

                //请求完成
                如果(s.global)
                    jQuery.event.trigger(ajaxComplete,[XML,S]);

                //处理全局AJAX计数器
                如果(s.global&安培;&安培;!--jQuery.active)
                    jQuery.event.trigger(ajaxStop);

                //处理结果
                如果(s.complete)
                    s.complete(XML,状态);

                jQuery的(IO).unbind()

                的setTimeout(函数()
                                    {   尝试
                                        {
                                            jQuery的(IO)上卸下摆臂();
                                            jQuery的(形式)上卸下摆臂();

                                        }赶上(五)
                                        {
                                            jQuery.handleError(S,XML,空,E);
                                        }

                                    },100)

                XML =空

            }
        }
        //超时检查
        如果(s.timeout大于0)
        {
            的setTimeout(函数(){
                //检查请求是否仍然发生
                如果uploadCallback(超时)(requestDone!);
            },s.timeout);
        }
        尝试
        {

            VAR形式=的jQuery(#+ formId);
            jQuery的(形式).attr('行动',s.url);
            jQuery的(形式).attr(方法,POST);
            jQuery的(形式).attr(目标,frameId);
            如果(form.encoding)
            {
                jQuery的(形式).attr('编码','多部分/表单数据);
            }
            其他
            {
                jQuery的(形式).attr(加密类型,多部分/表单数据);
            }
            jQuery的(形式).submit();

        }赶上(五)
        {
            jQuery.handleError(S,XML,空,E);
        }

        jQuery的('#'+ frameId).load(uploadCallback);
        返回{中止:函数(){}};

    },

    uploadHttpData:功能(R,输入){
        !VAR数据=类型;
        数据=类型==XML||数据 ? r.responseXML:r.responseText;
        //如果类型是脚本,EVAL它在全球范围内
        如果(类型==脚本)
            jQuery.globalEval(数据);
        //获取JavaScript对象,如果JSON使用。
        如果(类型==JSON)
            的eval(数据=+数据);
        //在HTML执行脚本
        如果(类型==HTML)
            jQuery的(&其中; DIV>中)的HTML(数据).evalScripts()。

        返回的数据;
    }
})
 
真上帝视角 奥斯卡绝妙一搓开天眼 赛季助攻已上双

解决方案

这是一个典型的微软的安全措施(如停止自动上传)。

这意味着你必须发起一个上传从实际用户自pressed按一下按钮。

样式的按钮,使它看起来像一个链接。

I'm having trouble uploading a file using a Javascript function that makes an Ajax call to a servlet. The file is uploaded perfectly when I use chrome, but not when I use IE8 (Go figure).

I used to have a file select button on the bottom of my form. When I clicked that button a function would be called and it would upload the file to the servlet using ajax. This worked perfectly in IE8, but the client wanted links instead. So now I have the links in the form, and the buttons hidden with css. The links call the click event of the buttons. Now the file uploading only works with Chrome, and not IE8.

The request never makes it to the servlet for some reason, and for some reason the ajax request returns success. Any idea what the problem might be?

Here is my code:

//Uploading a file
    $("#uploaded_file").change(function() {
        var filename = $(this).val();
        if(isAcceptable(filename)) {
            $.ajaxFileUpload
            (
                {
                    type: "POST",
                    url:'GenerateServlet', 
                    secureuri:false,
                    fileElementId:'uploaded_file',
                    dataType: 'json',
                    success: function (data, status)
                    {
                        if(typeof(data.error) != 'undefined')
                        {
                            if(data.error != '')
                            {
                                alert(data.error);
                            }else
                            {
                                alert(data.msg);
                            }
                        }
                        fillTemplate(data);

                    }
                }
            )
        }
        else if(filename.length > 0){
            $("#uploaded_file").val("");
            alert("Invalid File! Please select another file")
        }
    });

$("#upload_link").click(function() {
        document.getElementById('uploaded_file').click();
        return false;
    });

Here is the upload function:

jQuery.extend({


    createUploadIframe: function(id, uri)
    {
            //create frame
            var frameId = 'jUploadFrame' + id;
            var iframeHtml = '<iframe id="' + frameId + '" name="' + frameId + '" style="position:absolute; top:-9999px; left:-9999px"';
            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;
    },

    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));
        Console.log(form);
        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", [xml, s] );
                    } else
                        jQuery.handleError(s, xml, status);
                } catch(e) 
                {
                    status = "error";
                    jQuery.handleError(s, xml, status, e);
                }

                // The request was completed
                if( s.global )
                    jQuery.event.trigger( "ajaxComplete", [xml, 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, xml, null, 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, xml, null, e);
        }

        jQuery('#' + frameId).load(uploadCallback   );
        return {abort: function () {}}; 

    },

    uploadHttpData: function( r, type ) {
        var data = !type;
        data = type == "xml" || data ? r.responseXML : r.responseText;
        // 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" )
            eval( "data = " + data );
        // evaluate scripts within html
        if ( type == "html" )
            jQuery("<div>").html(data).evalScripts();

        return data;
    }
})

解决方案

That is a typical Microsoft security measure (e.g. to stop automated uploads).

That means you have to originate an upload from an actual user-pressed button click.

Style the button to make it look like a link instead.