原文出自:http://anxpp.com,转载请注明出处,谢谢!

    我还是决定记录一下。

    该JS由ajaxfileupload.js改造,原理是使用了Ifream,所以页面不会刷新。

改造后的ajaxfileupload.js:

jQuery.extend({
    createUploadIframe: function (id, uri) {
        var frameId = "jUploadFrame" + id;
        if (window.ActiveXObject) {
            var io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '" />');
            if (typeof uri == "boolean") {
                io.src = "javascript:false"
            } else {
                if (typeof uri == "string") {
                    io.src = uri
                }
            }
        } else {
            var io = document.createElement("iframe");
            io.id = frameId;
            io.name = frameId
        }
        io.style.position = "absolute";
        io.style.top = "-1000px";
        io.style.left = "-1000px";
        document.body.appendChild(io);
        return io
    }, createUploadForm: function (id, fileElementId) {
        var formId = "jUploadForm" + id;
        var fileId = "jUploadFile" + id;
        var form = $('<form  action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');
        for (var i in fileElementId) {
            var oldElement = jQuery("#" + fileElementId[i]);
            var newElement = jQuery(oldElement).clone();
            jQuery(oldElement).attr("id", fileId);
            jQuery(oldElement).before(newElement);
            jQuery(oldElement).appendTo(form)
        }
        $(form).css("position", "absolute");
        $(form).css("top", "-1200px");
        $(form).css("left", "-1200px");
        $(form).appendTo("body");
        return form
    }, addOtherRequestsToForm: function (form, data) {
        var originalElement = $('<input type="hidden" name="" value="">');
        for (var key in data) {
            name = key;
            value = data[key];
            var cloneElement = originalElement.clone();
            cloneElement.attr({
                "name": name,
                "value": value
            });
            $(cloneElement).appendTo(form)
        }
        return form
    }, ajaxFileUpload: function (s) {
        s = jQuery.extend({}, jQuery.ajaxSettings, s);
        var id = new Date().getTime();
        var form = jQuery.createUploadForm(id, s.fileElementId);
        if (s.data) {
            form = jQuery.addOtherRequestsToForm(form, 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) {
            }
            if (xml || isTimeout == "timeout") {
                requestDone = true;
                var status;
                try {
                    status = isTimeout != "timeout" ? "success" : "error";
                    if (status != "error") {
                        var data = jQuery.uploadHttpData(xml, s.dataType);
                        if (s.success) {
                            s.success(data, status)
                        }
                        if (s.global) {
                            jQuery.event.trigger("ajaxSuccess", [xml, s])
                        }
                    } else {
                    }
                } catch (e) {
                    status = "error";
                }
                if (s.global) {
                    jQuery.event.trigger("ajaxComplete", [xml, s])
                }
                if (s.global && !--jQuery.active) {
                    jQuery.event.trigger("ajaxStop")
                }
                if (s.complete) {
                    s.complete(xml, status)
                }
                jQuery(io).unbind();
                setTimeout(function () {
                    try {
                        $(io).remove();
                        $(form).remove()
                    } catch (e) {
                    }
                }, 100);
                xml = null
            }
        };
        if (s.timeout > 0) {
            setTimeout(function () {
                if (!requestDone) {
                    uploadCallback("timeout")
                }
            }, s.timeout)
        }
        try {
            var form = $("#" + formId);
            $(form).attr("action", s.url);
            $(form).attr("method", "POST");
            $(form).attr("target", frameId);
            if (form.encoding) {
                form.encoding = "multipart/form-data"
            } else {
                form.enctype = "multipart/form-data"
            }
            $(form).submit()
        } catch (e) {
        }
        if (window.attachEvent) {
            document.getElementById(frameId).attachEvent("onload", uploadCallback)
        } else {
            document.getElementById(frameId).addEventListener("load", uploadCallback, false)
        }
        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") {
            var data = r.responseText;
            var rx = new RegExp("<pre.*?>(.*?)</pre>", "i");
            var am = rx.exec(data);
            var data = (am) ? am[1] : "";
            eval("data = " + data)
        }
        if (type == "html") {
            jQuery("<div>").html(data).evalScripts()
        }
        return data
    }
});

Html代码:

    注意:这里的文件域的name属性,与后台接口中文件参数名对应(是一样的)。

<input type="file" name="files" id="files"/>
<input type="file" name="files" id="files1"/>
<input type="file" name="files" id="files2"/>
<input type="text" id="title_" name="title" placeholder="标题"/>
<input type="text" id="content_" name="content" placeholder="内容"/>
<input onclick="ajaxFileUpload()" type="button" value="上传" />

提交方法:

function ajaxFileUpload() {
    var params = {};
    params['title'] = $("#title_").val();
    params['content'] = $("#content_").val();
    $.ajaxFileUpload
    (
            {
                url: URLS['addArticle'],                        //用于文件上传的服务器端请求地址
                secureuri: false,                               //是否需要安全协议,一般设置为false
                fileElementId: ['files','files1','files2'],     //文件上传域的ID
                dataType: 'json',                               //返回值类型 一般设置为json
                data:params,
                type:'post',
                success: function (data, status)                //服务器成功响应处理函数
                {
                    $("#img1").attr("src", data.imgurl);
                    if (typeof (data.error) != 'undefined') {
                        if (data.error != '') {
                            alert(data.error);
                        } else {
                            alert(data.msg);
                        }
                    }
                },
                error: function (data, status, e)//服务器响应失败处理函数
                {
                    alert(e);
                }
            }
    )
    return false;
}

后台代码:

    @RequestMapping("/add")
    public Map<String, Object> addArticle(Article article,@RequestParam MultipartFile files[]){
        if(Utils.isNotNull(files))
            try{
                for(MultipartFile file : files)
                    FileUtils.writeByteArrayToFile(new File("c:/upload/"+file.getOriginalFilename()), file.getBytes());
            }catch(Exception e){
                e.printStackTrace();
            }
        return set(service.addArticle(article));
    }

需要的jar包:

    此处使用Maven

      <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.3</version>
        </dependency>

以上代码,如果没有文件会报错,后台如下改即可:

    public Map<String, Object> addArticle(Article article,HttpServletRequest request){
        if (request instanceof MultipartHttpServletRequest)
            try{
                List<MultipartFile> files = ((MultipartHttpServletRequest)request).getFiles("files");
                if(Utils.isNotNull(files))
                    for(MultipartFile file : files)
                        FileUtils.writeByteArrayToFile(new File("c:/upload/"+file.getOriginalFilename()), file.getBytes());
            }catch(Exception e){
                e.printStackTrace();
            }
        return set(service.addArticle(article));
    }

完成

至此,可以上传多文件了,并且同时可以上传附件。

仅作记录,代码完整且本人已测试通过(需要Jquery支持),所以不作多的解释。