SpringMVC+Ajax页面无刷新提交多个文件和数据

版权声明:http://blog.csdn.net/anxpp https://blog.csdn.net/anxpp/article/details/52081922

原文出自:http://blog.csdn.net/anxpp/article/details/52081922,转载请注明出处,谢谢!

    我还是决定记录一下。

    该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属性,与后台接口中文件参数名对应(是一样的)。

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

提交方法:

  1. function ajaxFileUpload() {
  2. var params = {};
  3. params['title'] = $("#title_").val();
  4. params['content'] = $("#content_").val();
  5. $.ajaxFileUpload
  6. (
  7. {
  8. url: URLS['addArticle'], //用于文件上传的服务器端请求地址
  9. secureuri: false, //是否需要安全协议,一般设置为false
  10. fileElementId: ['files','files1','files2'], //文件上传域的ID
  11. dataType: 'json', //返回值类型 一般设置为json
  12. data:params,
  13. type:'post',
  14. success: function (data, status) //服务器成功响应处理函数
  15. {
  16. $("#img1").attr("src", data.imgurl);
  17. if (typeof (data.error) != 'undefined') {
  18. if (data.error != '') {
  19. alert(data.error);
  20. } else {
  21. alert(data.msg);
  22. }
  23. }
  24. },
  25. error: function (data, status, e)//服务器响应失败处理函数
  26. {
  27. alert(e);
  28. }
  29. }
  30. )
  31. return false;
  32. }

后台代码:

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

需要的jar包:

    此处使用Maven

  1. <dependency>
  2. <groupId>commons-fileupload</groupId>
  3. <artifactId>commons-fileupload</artifactId>
  4. <version>1.3.1</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>commons-io</groupId>
  8. <artifactId>commons-io</artifactId>
  9. <version>2.3</version>
  10. </dependency>

完成

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

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

阅读更多 登录后自动展开
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页