准备
需要ajaxFileupload.js文件,在文章最后会贴出原码,因为这是原ajaxfileupload的改装版(网上找到的)

实现
虽然是用一个Ajax实现提交,然而form表单还是要分开写

java
<form id="addForm" >
    ······
</form>
<form id="ImgForm" enctype="multipart/form-data" >
    ······
</form>

js文件要注意附加表单序列化用的是serializeAarray()

java
$.ajaxFileUpload({
        url:"editItem.do",secureuri:false,fileElementId:$("input[name='file_upload']").attr("id"),dataType:'json',data:$("#addForm").serializeArray(),success:function(data){
            if(data.success){
                $("#Form_add").dialog("close");
                $("#Form_add").css("display","none");
                $('#list_data').datagrid('reload');
            }
        },error:function(data){
            alert("error"+data.msg);
        }
    });

后台对于表单,Spring MVC该怎么接收怎么接收,比如下面的 item自定义变量

java
@RequestMapping(value="/editItem.do")
    public void editItem(Item item,HttpServletResponse response,HttpServletRequest request) throws FileNotFoundException,IOException{

    ·······
    CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
            if (multipartResolver.isMultipart(request)) {
                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
                Iterator<String> iter = multiRequest.getFileNames();
                while (iter.hasNext()) {
                    multipartfile file = multiRequest.getFile(iter.next());
                    if(!file.isEmpty()){
                        savePicture(file,request);//保存图片
                    }
                }
            }
}
java
//文件保存到服务器上
    protected String savePicture(multipartfile file,HttpServletRequest request)
            throws IOException,FileNotFoundException {
// System.out.println("图片上传成功");
        String ImagePath = request.getSession().getServletContext().getRealPath("/static/img");
        File targetfile = new File(ImagePath,file.getoriginalFilename());
        Date date = new Date(System.currentTimeMillis());
        if(targetfile.exists()){
            targetfile = new File(ImagePath,file.getoriginalFilename() + date.toString());
        }
        InputStream ins = file.getInputStream();
        FileOutputStream fos = new FileOutputStream(targetfile);

        byte b[] = new byte[1024];
        int temp = 0;

        while((temp = ins.read(b)) != -1){
            fos.write(b,0,temp);
        }

        fos.close();
        ins.close();
        return targetfile.getName();
    }

附件

下面给出ajaxfileupload.js的文件

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) {
        //create form 
        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",s]);
                    } else
                        jQuery.handleError(s,status);
                } catch (e) {
                    status = "error";
                    jQuery.handleError(s,status,e);
                }
                // The request was completed
                if (s.global)
                    jQuery.event.trigger("ajaxComplete",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,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,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,e) {
        // If a local callback was specified,fire it
        if (s.error) {
            s.error.call(s.context || s,e);
        }
        // Fire the global callback
        if (s.global) {
            (s.context ? jQuery(s.context) : jQuery.event).trigger("ajaxError",[xhr,s,e]);
        }
    }
})

利用ajaxFileupload实现表单和图片同时上传的更多相关文章

  1. HTML5新增form控件和表单属性实例代码详解

    这篇文章主要介绍了HTML5新增form控件和表单属性实例代码详解,需要的朋友可以参考下

  2. canvas中普通动效与粒子动效的实现代码示例

    canvas用于在网页上绘制图像、动画,可以将其理解为画布,在这个画布上构建想要的效果。本文详细的介绍了粒子特效,和普通动效进行对比,非常具有实用价值,需要的朋友可以参考下

  3. jquery点赞功能实现代码 点个赞吧!

    点赞功能很多地方都会出现,如何实现爱心点赞功能,这篇文章主要为大家详细介绍了jquery点赞功能实现代码,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  4. H5混合开发app如何升级的方法

    本篇文章主要介绍了H5混合开发app如何升级的方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

  5. canvas学习和滤镜实现代码

    这篇文章主要介绍了canvas学习和滤镜实现代码,利用 canvas,前端人员可以很轻松地、进行图像处理,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  6. localStorage的过期时间设置的方法详解

    这篇文章主要介绍了localStorage的过期时间设置的方法详解的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

  7. 详解HTML5 data-* 自定义属性

    这篇文章主要介绍了详解HTML5 data-* 自定义属性的相关资料,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

  8. HTML5的postMessage的使用手册

    HTML5提出了一个新的用来跨域传值的方法,即postMessage,这篇文章主要介绍了HTML5的postMessage的使用手册的相关资料,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

  9. 教你使用Canvas处理图片的方法

    本篇文章主要介绍了教你使用Canvas处理图片的方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

  10. HTML5表单验证特性(知识点小结)

    这篇文章主要介绍了HTML5表单验证特性的一些知识点,本文通过实例代码截图的形式给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

随机推荐

  1. xe-ajax-mock 前端虚拟服务

    最新版本见Github,点击查看历史版本基于XEAjax扩展的Mock虚拟服务插件;对于前后端分离的开发模式,ajax+mock使前端不再依赖后端接口开发效率更高。CDN使用script方式安装,XEAjaxMock会定义为全局变量生产环境请使用xe-ajax-mock.min.js,更小的压缩版本,可以带来更快的速度体验。

  2. vue 使用 xe-ajax

    安装完成后自动挂载在vue实例this.$ajaxCDN安装使用script方式安装,VXEAjax会定义为全局变量生产环境请使用vxe-ajax.min.js,更小的压缩版本,可以带来更快的速度体验。cdnjs获取最新版本点击浏览已发布的所有npm包源码unpkg获取最新版本点击浏览已发布的所有npm包源码AMD安装require.js安装示例ES6Module安装通过Vue.use()来全局安装示例./Home.vue

  3. AJAX POST数据中文乱码解决

    前端使用encodeURI进行编码后台java.net.URLDecoder进行解码编解码工具

  4. Koa2框架利用CORS完成跨域ajax请求

    实现跨域ajax请求的方式有很多,其中一个是利用CORS,而这个方法关键是在服务器端进行配置。本文仅对能够完成正常跨域ajax响应的,最基本的配置进行说明。这样OPTIONS请求就能够通过了。至此为止,相当于仅仅完成了预检,还没发送真正的请求呢。

  5. form提交时,ajax上传文件并更新到&lt;input&gt;中的value字段

  6. ajax的cache作用

    filePath="+escape;},error:{alert;}});解决方案:1.加cache:false2.url加随机数正常代码:网上高人解读:cache的作用就是第一次请求完毕之后,如果再次去请求,可以直接从缓存里面读取而不是再到服务器端读取。

  7. 浅谈ajax上传文件属性contentType = false

    默认值为contentType="application/x-www-form-urlencoded".在默认情况下,内容编码类型满足大多数情况。在这里,我们主要谈谈contentType=false.在使用ajax上传文件时:在其中先封装了一个formData对象,然后使用post方法将文件传给服务器。说到这,我们发现在JQueryajax()方法中我们使contentType=false,这不是冲突了吗?这就是因为当我们在form标签中设置了enctype=“multipart/form-data”,

  8. 909422229_ajaxFileUpload上传文件

    ajaxFileUpload.js很多同名的,因为做出来一个很容易。我上github搜AjaxFileUpload出来很多类似js。ajaxFileUpload是一个异步上传文件的jQuery插件传一个不知道什么版本的上来,以后不用到处找了。语法:$.ajaxFileUploadoptions参数说明:1、url上传处理程序地址。2,fileElementId需要上传的文件域的ID,即的ID。3,secureuri是否启用安全提交,默认为false。4,dataType服务器返回的数据类型。6,error

  9. AJAX-Cache:一款好用的Ajax缓存插件

    原文链接AJAX-Cache是什么Ajax是前端开发必不可少的数据获取手段,在频繁的异步请求业务中,我们往往需要利用“缓存”提升界面响应速度,减少网络资源占用。AJAX-Cache是一款jQuery缓存插件,可以为$.ajax()方法扩展缓存功能。

  10. jsf – Ajax update/render在已渲染属性的组件上不起作用

    我试图ajax更新一个有条件渲染的组件。我可以确保#{user}实际上是可用的。这是怎么引起的,我该如何解决呢?必须始终在ajax可以重新呈现之前呈现组件。Ajax正在使用JavaScriptdocument.getElementById()来查找需要更新的组件。但是如果JSF没有将组件放在第一位,那么JavaScript找不到要更新的内容。解决方案是简单地引用总是渲染的父组件。

返回
顶部