ajaxfileupload.js组件的确好用,但是那个返回值格式也太恶心了吧!
让人家定义一个dataType:"json",最后给返回一堆html,什么意思?也许是鄙人愚钝,索性修改了下源代码的处理函数,手动返回json得了。
修改代码:
大约在ajaxfileupload.js 的185行左右,有这么个函数:uploadHttpData
原始代码与改后代码对比:

一,修改ajaxfileupload.js源码

    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; */ var data =r.responseText; var start = data.indexOf("{"); var end = data.indexOf("}"); var jsonStr = data.substring(start,end+1); return (jsonStr instanceof Object)?jsonStr:eval("(" + jsonStr + ")"); }
就是用来处理了下返回值,这个函数返回的值就直接传递到了我们文件上传的success回调函数json值了。直接当对象使用就ok了。

二,文件上传js代码

    $.ajaxFileUpload({
        url:url,            //需要链接到服务器地址
        type: 'post',//请求方式  当要提交自定义参数时,这个参数要设置成post
        fileElementId:uploadFileName,                        //文件选择框的id属性
        dataType: 'json',                                     //服务器返回的格式,可以是json, xml
        success: function (data, status)            //相当于java中try语句块的用法
        {
          if(data.status==200){
            alert('上传成功');
          }else{
            alert('上传失败');
          }
        },
        error: function (data, status, e)            //相当于java中catch语句块的用法
        {       //alert("上传失败"+e);
            alert('error message');
        }
    });

三,文件上传spring mvc 代码

    @RequestMapping("/uploadFile.do")
    @ResponseBody
    public Map uploadFile(Model model, HttpServletRequest request,
            HttpServletResponse response,
            @RequestParam("uploadFileName") MultipartFile fileUpload)
            throws Exception {
        Map result = new HashMap();
        String fileName = fileUpload.getOriginalFilename();
        // 文件保存
        try {
            File newFile = new File(uploadPath + fileName);
            fileUpload.transferTo(newFile);
        } catch (Exception e) {
            result.put("status", "300");
            log.error("文件上传保存出错", e);
            return result;
        }
}

具体上传细节就不赘述了,网上很多,有问题请留言!

转载自:https://blog.csdn.net/guxing820/article/details/40349971