js上传文件

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

用到两个对象
第一个对象:FormData
第二个对象:XMLHttpRequest
眼下新版的Firefox 与 Chrome 等支持HTML5的浏览器完美的支持这两个对象,但IE9尚未支持 FormData 对象。还在用IE6 ? 仅仅能仰天长叹....
有了这两个对象。我们能够真正的实现Ajax方式上传文件。
演示样例代码:
<!DOCTYPE html>
<html>
<head>
    <title>Html5 Ajax 上传文件</title>
    <script type="text/javascript">
        function UpladFile() {
            var fileObj = document.getElementByIdx_x_x("file").files[0]; // 获取文件对象
            var FileController = "../file/save";                    // 接收上传文件的后台地址
            // FormData 对象
            var form = new FormData();
            form.append("author", "hooyes");                        // 能够添加表单数据
            form.append("file", fileObj);                           // 文件对象
            // XMLHttpRequest 对象
            var xhr = new XMLHttpRequest();
            xhr.open("post", FileController, true);
            xhr.onload = function () {
                alert("上传完毕!");
            };
            xhr.send(form);
        }
</script>
</head>
<body>
<input type="file" id="file" name="img1" />
<input type="button" onclick="UpladFile()" value="上传" />
</body>
</html>

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:

<script type="text/javascript" src="<%=basePath%>resources/js/jquery-1.2.1.js"></script>
<script type="text/javascript" src="<%=basePath%>resources/js/ajaxfileupload.js"></script>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ include file="/base.jsp" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>ajax文件上传</title>
    
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <link rel="stylesheet" type="text/css" href="validate/ajaxfileupload.css" />
    <script type="text/javascript" src="validate/jquery-1.6.2.min.js"></script>
    <script type="text/javascript" src="validate/ajaxfileupload.js" ></script>
    <script type="text/javascript">
    $(function(){
       //上传图片
       $("#btnUpload").click(function() {
               alert(ajaxFileUpload());
       });
    });
    function ajaxFileUpload() {
        // 開始上传文件时显示一个图片
        $("#wait_loading").ajaxStart(function() {
            $(this).show();
        // 文件上传完毕将图片隐藏起来
        }).ajaxComplete(function() {
            $(this).hide();
        });
        var elementIds=["flag"]; //flag为id、name属性名
        $.ajaxFileUpload({
            url: 'uploadAjax.htm',
            type: 'post',
            secureuri: false, //一般设置为false
            fileElementId: 'file', // 上传文件的id、name属性名
            dataType: 'text', //返回值类型。一般设置为json、application/json
            elementIds: elementIds, //传递參数到server
            success: function(data, status){  
                alert(data);
            },
            error: function(data, status, e){
                alert(e);
            }
        });
        //return false;
    }
    </script>
  </head>
 
  <body>
    <div id="wait_loading" style="padding: 50px 0 0 0;display:none;">
        <div style="width: 103px;margin: 0 auto;"><img src="<%=path %>/images/loading.gif"/></div>
        <br></br>
        <div style="width: 103px;margin: 0 auto;"><span>请稍等...</span></div>
        <br></br>
    </div>
    <input type="file" id="file" name="file"><br/>
    <input type="hidden" id="flag" name="flag" value="ajax文件上传"/>
    <input type="button" id="btnUpload" value="上传图片" />
  </body>
</html>

后台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 = '<iframe id="' + frameId + '" name="' + frameId + '" style="position:absolute; top:-9999px; left:-9999px"'; //创建iframe元素
        if (window.ActiveXObject) {//推断浏览器是否支持ActiveX控件
            if (typeof uri == 'boolean') {
                iframeHtml += ' src="' + 'javascript:false' + '"';
            }            else if (typeof uri == 'string') {
                iframeHtml += ' src="' + uri + '"';
            }
        }
        iframeHtml += ' />';
        jQuery(iframeHtml).appendTo(document.body); //将动态iframe追加到body中
        return jQuery('#' + frameId).get(0); //返回iframe对象
    },
    createUploadForm: function (id, fileElementId, data) {//id为当前系统时间字符串,fileElementId为页面<input type='file' />的id。data的值须要依据传入json的键来决定
        //create form    
        var formId = 'jUploadForm' + id; //给form加入一个独一无二的id
        var fileId = 'jUploadFile' + id; //给<input type='file' />加入一个独一无二的id
        var form = jQuery('<form  action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data" ></form>'); //创建form元素
        if (data) {//通常为false
            for (var i in data) {
                jQuery('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendTo(form); //依据data的内容。创建隐藏域,这部分我还不知道是什么时候用到。预计是传入json的时候,假设默认传一些參数的话要用到。
            }
        }        var oldElement = jQuery('#' + fileElementId); //得到页面中的<input type='file' />对象
        var newElement = jQuery(oldElement).clone(); //克隆页面中的<input type='file' />对象
        jQuery(oldElement).attr('id', fileId); //改动原对象的id
        jQuery(oldElement).before(newElement); //在原对象前插入克隆对象
        jQuery(oldElement).appendTo(form); //把原对象插入到动态form的结尾处
        //set attributes
        jQuery(form).css('position', 'absolute'); //给动态form加入样式,使其浮动起来,
        jQuery(form).css('top', '-1200px');
        jQuery(form).css('left', '-1200px');
        jQuery(form).appendTo('body'); //把动态form插入到body中
        return form;
    },
    ajaxFileUpload: function (s) {//这里s是个json对象。传入一些ajax的參数
        // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout        
        s = jQuery.extend({}, jQuery.ajaxSettings, s); //此时的s对象是由jQuery.ajaxSettings和原s对象扩展后的对象
        var id = new Date().getTime(); //取当前系统时间,目的是得到一个独一无二的数字
        var form = jQuery.createUploadForm(id, s.fileElementId, (typeof (s.data) == 'undefined' ? false : s.data)); //创建动态form
        var io = jQuery.createUploadIframe(id, s.secureuri); //创建动态iframe
        var frameId = 'jUploadFrame' + id; //动态iframe的id
        var formId = 'jUploadForm' + id; //动态form的id
        // Watch for a new set of requests
        if (s.global && !jQuery.active++) {//当jQuery開始一个ajax请求时发生
            jQuery.event.trigger("ajaxStart"); //触发ajaxStart方法
        }        var requestDone = false; //请求完毕标志
        // Create the request object
        var xml = {};        if (s.global)
            jQuery.event.trigger("ajaxSend", [xml, s]); //触发ajaxSend方法
        // Wait for a response to come back
        var uploadCallback = function (isTimeout) {//回调函数
            var io = document.getElementById(frameId); //得到iframe对象
            try {                if (io.contentWindow) {//动态iframe所在窗体对象是否存在
                    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) {//动态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("<div>").html(data).evalScripts();        return data;
    }
})
 

结论:

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

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

posted @ 2017-07-06 11:51  lytwajue  阅读(1333)  评论(0编辑  收藏  举报