web上传下载之--ajaxFileUpload

很多ajaxFileUpload.js 是同名的,有的却不能用,今天上传一个版本,示例代码是应用在avalon框架上的(其实哪个框架都可以用,装逼一下,勿喷)。

进入正题:

第一步:ajaxFileUpload.js在最下面有。

第二步:先讲一下用法吧,copy一下别人共享的,已经很详细了,

语法:$.ajaxFileUpload([options])

  options参数说明:

1、url            上传处理程序地址。  
2,fileElementId       需要上传的文件域的ID,即<input type="file">的ID。
3,secureuri        是否启用安全提交,默认为false。
4,dataType        服务器返回的数据类型。可以为xml,script,json,html。如果不填写,jQuery会自动判断。
5,success        提交成功后自动执行的处理函数,参数data就是服务器返回的数据。
6,error          提交失败自动执行的处理函数。
7,data           自定义参数。这个东西比较有用,当有数据是与上传的图片相关的时候,这个东西就要用到了。
8, type            当要提交自定义参数时,这个参数要设置成post

错误提示:

1,SyntaxError: missing ; before statement错误
  如果出现这个错误就需要检查url路径是否可以访问
2,SyntaxError: syntax error错误
  如果出现这个错误就需要检查处理提交操作的服务器后台处理程序是否存在语法错误
3,SyntaxError: invalid property id错误
  如果出现这个错误就需要检查文本域属性ID是否存在
4,SyntaxError: missing } in XML expression错误
  如果出现这个错误就需要检查文件name是否一致或不存在
5,其它自定义错误
  大家可使用变量$error直接打印的方法检查各参数是否正确,比起上面这些无效的错误提示还是方便很多。

html:

           <tr>
                <td style="width:120px;text-align:right;"><span>类型中图片&nbsp;&nbsp;</span></td>&nbsp;&nbsp;
                <td style="text-align:left;height:55px">
                    <input ms-attr-disabled="isCanEdit" id="pic" type="file" name="file" style="width:50%;text-align:left" />
                    <a class="ui-searchBtn" href="javascript:;" ms-on-click="uploadFile('pic')">上传</a>
                </td>
            </tr>

js:

          uploadFile: function(elId) {
                if ($("#" + elId).val() === "") {
                    alert("请选择上传文件!");
                    return;
                }
                $.ajaxFileUpload({
                    url: svMap.get('xRequestPic'),
                    secureuri: false,
                    fileElementId: elId,
                    dataType: 'json',
                    success: function(data, status) {
                        var trValue = $("#" + elId).closest('tr').next();
                        trValue.show();
                        trValue.find('td').last().text(data.logo_url);
                        if (typeof(data.error) != 'undefined') {
                            if (data.error != '') {
                                alert(data.error);
                            } else {
                                alert(data.message);
                            }
                        }
                    },
                    error: function(data, status, e) {
                        alert(e);
                    }
                })
            },

第三步:第二步代码有些没用的,我把自己项目上的原封不动的粘上去了,一开始就说了,我用的avalon,哈哈。

后台java接收数据流

@ResponseBody
    @RequestMapping(value = "/xmlRequestUpLoading", method = RequestMethod.POST)
    public Map xmlRequestUpLoading(HttpServletRequest req, HttpSession session) {
        Map condmsgMap = new HashMap<String, List>();
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) req;
        MultipartFile file = null;
        file = multipartRequest.getFile("file");// 获取上传文件名
        String limit=req.getParameter("limit");
        if(limit!=null&&limit.equals("1")&&file.getSize()>20480){
            condmsgMap.put("message", "请上传不超过20Kb的图片!");
            setReturnMap("401", "超过20Kb!", condmsgMap);
            return condmsgMap;
        }
        StringBuffer logo_URL = new StringBuffer();
        if (file != null && file.getSize()>0) {
            String appDirPath = req.getSession().getServletContext().getRealPath("/");
            String realFilename = file.getOriginalFilename().substring(file.getOriginalFilename().indexOf("."), file.getOriginalFilename().length());
            realFilename.replaceAll("\\.", "");
            if(isValidPermit(realFilename)){
                condmsgMap.put("message", "上传的文件格式不正确!");
                setReturnMap("-1", "调用成功!", condmsgMap);
            }
            realFilename = DATE_FORMAT.format(new Date())+realFilename;
            String ctxPath = PropertiesUtils.getproperties("logo.pic.url", "uploadpic");
            ctxPath = appDirPath + ctxPath;
            File dirPath = new File(ctxPath);
            if (!dirPath.exists()) {
                dirPath.mkdir();
            }
            File uploadFile = new File(ctxPath +"/"+ realFilename);
            try {
                FileCopyUtils.copy(file.getBytes(), uploadFile);
            } catch (Exception e) {
                logger.error("上传Logo图片异常:{}", e);
            }
            StringBuffer tempBuffer = new StringBuffer();
            StringBuffer appContextPath = req.getRequestURL();
            tempBuffer.append(appContextPath.substring(0, appContextPath.indexOf("api")));
            tempBuffer.append(PropertiesUtils.getproperties("logo.pic.url", "uploadpic\\"));
            logo_URL.append(tempBuffer.substring(0, tempBuffer.length())).append("/").append(realFilename);
        }

        condmsgMap.put("message", "上传成功!");
        condmsgMap.put("logo_url", logo_URL.toString());
        setReturnMap("0", "上传成功!", condmsgMap);
        return condmsgMap;
    }


ajaxfileupload.js源码如下:


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) {
        //15.11.28 modify
        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) {
                if (data[i].name != null && data[i].value != null) {
                    jQuery('<input type="hidden" name="' + data[i].name + '" value="' + data[i].value + '" />').appendTo(form);
                } else {
                    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));
        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;
        if (!type)
            data = r.responseText;
        if (type == "xml")
            data = r.responseXML;
        //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") {
            Fix the issue that it always throws the error "unexpected token '<'"///  
            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;
    },

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

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


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值