AjaxUpload上传控件、JQuery控件

前端之家收集整理的这篇文章主要介绍了AjaxUpload上传控件、JQuery控件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

AjaxUpload上传控件,使用该控件可以实现带进度条的上传
ajaxfileupload.js

//String retxt ="{error:'',\n msg:'success'\n}"; 调用插件,返回字符串格式
//response.getWriter().print(retxt); jsp代码

jQuery.extend({
    createUploadIframe: function (id,uri) {
        //创建 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) {
        //创建 frame 
        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);

        //设置属性
        jQuery(form).css('position','absolute');
        jQuery(form).css('top','-1200px');
        jQuery(form).css('left','-1200px');
        jQuery(form).appendTo('body');
        return form;
    },ajaxFileUpload: function (s) {
        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;
        // 监控请求
        if (s.global && !jQuery.active ++) {
            jQuery.event.trigger("ajaxStart");
        }
        var requestDone = false;
        // 创建请求对象
        var xml = {};
        if (s.global)
            jQuery.event.trigger("ajaxSend",[xml,s]);
        //等待一个响应返回
        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) {
                //alert("666666");
                jQuery.handleError(s,xml,null,e);
            }
            if (xml || isTimeout == "timeout") {
                requestDone = true;
                var status;
                try {

                    status = isTimeout != "timeout" ? "success" : "error";

                    //请求成功
                    if (status != "error") {

                        // 处理数据 //根据传送的type类型,返回json对象,此时返回的data就是后台操作后的返回结果
                        var data = jQuery.uploadHttpData(xml,s.dataType);
                        if (s.success)
                            s.success(data,status);
                        // 触发全局返回
                        if (s.global){
                            jQuery.event.trigger("ajaxSuccess",s]);
                        }                            
                        //alert("if");
                    } else{
                        jQuery.handleError(s,status);
                    }

                } catch (e) {
                    //alert("777777");
                    status = "error";
                    jQuery.handleError(s,status,e);
                }

                // 请求完成
                if (s.global)
                    jQuery.event.trigger("ajaxComplete",s]);

                // 处理全局AJAX计数器
                if (s.global && ! --jQuery.active)
                    jQuery.event.trigger("ajaxStop");

                // 处理结果
                if (s.complete)
                    s.complete(xml,status);

                jQuery(io).unbind();

                setTimeout(function () {
                    try {
                        jQuery(io).remove();
                        jQuery(form).remove();

                    } catch (e) {
                        //alert("888888");
                        jQuery.handleError(s,e);
                    }

                },100);

                xml = null;

            }
        }
        // 超时检查
        if (s.timeout > 0) {
            setTimeout(function () {
                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) {
            //alert("9999");
            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;
        if (type == "script")
            jQuery.globalEval(data);
        if (type == "json")
            eval("data = " + data);
        if (type == "html")
            jQuery("<div>").html(data).evalScripts();
        return data;
    }
});

处理上传操作的JS,由上传按钮的事件调用。接收参数为服务器处理文件的jsp页面或者注册的服务,第二个参数为上传成功后需要显示用户的反馈信息。
注:此函数也可以实现下载,只需将fileElementId引用的input控件的url指向服务器的某个能返回流的服务或者界面,就会在客户端弹出下载界面。urlStr = input控件指向的文件名即可。

function ajaxFileUpload(urlStr,showMegStr) {
        var form = $("<form>"); 
        form.ajaxStart(function () {
                alert("上传开始");//此处可以利用JS生成上传的动画
        });
        form.ajaxComplete(function () {             
                alert("上传结束");
        });

        jQuery.ajaxFileUpload(
        {
                url: urlStr,secureuri: @H_941_404@false,fileElementId: 'upload_attach',dataType: 'json',data: { 'name': 'logan','id': 'id' },success: function (data,status) { //data后台jsp返回结果,status Ajaxfileupload控件返回的状态
                    if (typeof (data.error) != '') {
                        if (data.error == '') {
                            alert(showMegStr);

                        } else {
                            alert("上传文件格式不正确!");
                        }
                    }
                },error: function (data,e) {
                    alert(e);
                }
        });

        return @H_941_404@true;
}

用户界面:
selectFilePage.jsp

<html>
<head>
<title id="title"></title>
</head>
<body>

<!-- 标题栏 -->
    <div class='' id='filePageNagText'><span>浏览文件</span></div>  
<!-- 列表table -->


    <form id="form1" name="form1" encType="multipart/form-data" method="post" target="hidden_frame">
        <div id ="AttachDiv" >&nbsp;
        <input type="file" name="upload_attach" id="upload_attach" > &nbsp;
        <iframe name='hidden_frame' id="hidden_frame" style='display: none'></iframe>
        </div>
    </form>

</body>
</html>

后端处理上传文件的JSP,接收文件流并写入服务器本地磁盘

<%@ page import="java.io.*,java.util.*,javax.servlet.*" %>
<%@ page import="javax.servlet.http.*" %>
<%@ page import="org.apache.commons.fileupload.*" %>
<%@ page import="org.apache.commons.fileupload.disk.*" %>
<%@ page import="org.apache.commons.fileupload.servlet.*" %>
<%@ page import="org.apache.commons.io.output.*" %>
<%@ page import="inforunner.oatransmanager.PublicLib" %>
<%@ page import="inforunner.util.ConfigPathUtils" %>
<%@page import="java.util.HashMap"%>
<%@page import="java.util.List"%>
<%@page import="java.util.Map"%>
<%

   int maxFileSize = 200 * 1024 * 1024;
   int maxMemSize = 200 * 1024 * 1024;
   ServletContext context = pageContext.getServletContext();
   Map<String,String > map = new HashMap();
    // String realPath = request.getRealPath("/platform/inforunner/TransUI/upload");
   String filePath = ConfigPathUtils.getEnvelopUploadPath(); //读配置文件公文上传目录request.getRealPath("/platform/inforunner/TransUI/upload");
   //System.out.println("filePath="+filePath );
    String retXML= "";
   // 验证上传内容的类型
   String contentType = request.getContentType();

   File file = null;

   if ((contentType.indexOf("multipart/form-data") >= 0)) {

      DiskFileItemFactory factory = new DiskFileItemFactory();

      // 设置内存中存储文件的最大值
      factory.setSizeThreshold(maxMemSize);

      // 本地存储的数据大于 maxMemSize.
      //factory.setRepository(new File("c:\\temp"));


     // 创建一个新的文件上传处理程序
      ServletFileUpload upload = new ServletFileUpload(factory);
      // 设置最大上传文件大小
      upload.setSizeMax( maxFileSize );
      try{ 
         // 解析获取文件
         List fileItems = upload.parseRequest(request);

         // 处理上传文件
         Iterator i = fileItems.iterator();


         while ( i.hasNext () ) 
         {
            FileItem fi = (FileItem)i.next();
            if ( !fi.isFormField () )   
            {
            // 获取上传文件的参数
            String fieldName = fi.getFieldName();
            String fileName = fi.getName();
            boolean isInMemory = fi.isInMemory();
            long sizeInBytes = fi.getSize();
            //检查上传文件夹是否存在,不存在就创建
            File uploadFile = new File(filePath);
            if (!uploadFile.exists() && !uploadFile.isDirectory()) {
                    uploadFile.mkdirs();
            }

            // 写入文件
            if( fileName.lastIndexOf("\\") >= 0 ){
                file = new File( filePath,fileName.substring( fileName.lastIndexOf("\\"))) ;
            }else{
                file = new File( filePath,fileName.substring(fileName.lastIndexOf("\\")+1)) ;
            }



                fi.write( file ) ;
                map.put("msg","true" );
                map.put("error","" );
                System.out.println("Uploaded Filename: " + filePath + "/"   +fileName);
            }
         }
         //out.println("</body>");
         //out.println("</html>");
      }catch(Exception ex) {
         System.out.println(ex);
         map.put("msg","false" );
         map.put("error",ex.toString() );
     }
   }
    response.setStatus(200);  
    String retxt ="{error:'',msg:'success',fileName:''}";  //此处返回格式依据,ajaxfileupload.js插件
    response.getWriter().print(retxt);  
%>
原文链接:https://www.f2er.com/ajax/163247.html

猜你在找的Ajax相关文章