js上传文件

2021-07-03 06:04

阅读:576

YPE html>

一、原始的XMLHttpRequestjs上传文件过程(參考地址:http://blog.sina.com.cn/s/blog_5d64f7e3010127ns.html)

用到两个对象
第一个对象:FormData
第二个对象:XMLHttpRequest
眼下新版的Firefox 与 Chrome 等支持HTML5的浏览器完美的支持这两个对象,但IE9尚未支持 FormData 对象。还在用IE6 ? 仅仅能仰天长叹....
有了这两个对象。我们能够真正的实现Ajax方式上传文件。
演示样例代码:



    Html5 Ajax 上传文件
   





java 代码:

    private File img1;

    private String img1FileName;

    private String img1ContentType;
    
    private String saveFile() {
        int lastDotIndex = img1FileName.lastIndexOf(".");
        String imgType = img1FileName.substring(lastDotIndex - 1, img1FileName.length());
        String tempName = UploadImgTempFilePath.getUploadFilePath() + UUID.randomUUID() + imgType;
        try {

            // 建立文件输出流
            FileOutputStream fos = new FileOutputStream(tempName);
            // 建立文件上传流
            FileInputStream fis = new FileInputStream(img1);
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = fis.read(buffer)) > 0) {
                fos.write(buffer, 0, len);
            }
            fis.close();
            fos.close();
        } catch (Exception e) {
            return null;
        }
        return tempName;

    }


二、 使用ajax的插件ajaxfileupload(參考地址:http://www.cnblogs.com/linjiqin/p/3530848.html)

引入js:



String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>



 


   
    
    ajax文件上传
    
   
   
   
        
   
   
   
   
   
   
 
 
 
   
   

   
   
 

后台java代码类似。

三、ajaxfileupload源代码分析(參考地址:http://blog.csdn.net/it_man/article/details/43800957)

jQuery.extend({
    createUploadIframe: function (id, uri) {//id为当前系统时间字符串。uri是外部传入的json对象的一个參数
        //create frame
        var frameId = ‘jUploadFrame‘ + id; //给iframe加入一个独一无二的id
        var iframeHtml = ‘

io.contentWindow.document.body.innerHTML : null;
                    xml.responseXML = io.contentWindow.document.XMLDocument ? io.contentWindow.document.XMLDocument : io.contentWindow.document;
                } else if (io.contentDocument) {//动态iframe的文档对象是否存在
                    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") {//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); //依据传送的type类型,返回json对象,此时返回的data就是后台操作后的返回结果
                        // 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();//移除iframe的事件处理程序
                setTimeout(function () {//设置超时时间
                    try {
                        jQuery(io).remove();//移除动态iframe
                        jQuery(form).remove();//移除动态form
                    } 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);//传入的ajax页面导向url
            jQuery(form).attr(‘method‘, ‘POST‘);//设置提交表单方式
            jQuery(form).attr(‘target‘, frameId);//返回的目标iframe。就是创建的动态iframe
            if (form.encoding) {//选择编码方式
                jQuery(form).attr(‘encoding‘, ‘multipart/form-data‘);
            }            else {
                jQuery(form).attr(‘enctype‘, ‘multipart/form-data‘);
            }
            jQuery(form).submit();//提交form表单
        } catch (e) {
            jQuery.handleError(s, xml, null, e);
        }
        jQuery(‘#‘ + frameId).load(uploadCallback); //ajax 请求从server载入数据。同一时候传入回调函数
        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("

").html(data).evalScripts();        return data;
    }
})
 

结论:

查看ajax的方式也是通过构建type=file的方式,用form上传的。所以假设能通过form方式提交的话,就通过form提交吧。

别人的使用实例,比較好:http://www.cnblogs.com/kissdodog/archive/2012/12/15/2819025.html

上一篇:JSDOM

下一篇:jquery选择器


评论


亲,登录后才可以留言!