上传文件 --ajax异步上传并回显 -- springMVC组件

添加依赖

文件异步上传
```xml
    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.4</version>
    </dependency>
    <dependency>
        <groupId>commons-fileupload</groupId>
        <artifactId>commons-fileupload</artifactId>
        <version>1.3.1</version>
    </dependency>
</dependencies>

在springmvc.xml中配置文件上传解析器

<!--    设置文件上传核心文件-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

</bean>

1. 上传文件 --ajax异步上传并回显 – springMVC组件

1.1 前端上传图片

文件选择

<tr>
	<td class="three">图片介绍</td>
	<!--ajax接收返回的图片位置并加载到imgDiv中-->
    <td> <br><div id="imgDiv" style="display:block; width: 40px; height: 50px;"></div><br><br><br><br>
    <!--选择文件,触发点击事件将文件传给Ajax异步上传-->
    <input type="file" id="pimage" name="pimage" onchange="fileChange()" >
        <span id="imgName" ></span><br>

    </td>

Ajax异步提交事件 – 采用ajaxfileupload.js文件(封装ajax异步上传的功能)

<!-- 引入ajaxfileupload.js-->
<script type="text/javascript" src="${pageContext.request.contextPath }/js/ajaxfileupload.js"></script>

<script type="text/javascript">
    function fileChange(){
    
    //注意:此处不能使用jQuery中的change事件,因此仅触发一次,因此使用标签的:onchange属性
        $.ajaxFileUpload({
    
    
            url: '/prod/ajaxImg.action',//用于文件上传的服务器端请求地址
            secureuri: false,//是否需要安全协议一般设置为false
            fileElementId: 'pimage',//文件上传控件的id属性  <input type="file" id="pimage" name="pimage" />
            dataType: 'json',//返回值类型 一般设置为json
            success: function(obj) //服务器成功响应处理函数
            {
    
    
                $("#imgDiv").empty();  //清空原有数据
                //创建img 标签对象
                var imgObj = $("<img>");
                //给img标签对象追加属性
                imgObj.attr("src","/image_big/"+obj.imgurl);
                imgObj.attr("width","100px");
                imgObj.attr("height","100px");
                //将图片img标签追加到imgDiv末尾
                $("#imgDiv").append(imgObj);
            },
            error: function (e)//服务器响应失败处理函数
            {
    
    
                alert(e.message);
            }
        });
    }
</script>

1.2 在ProductInfoAction中添加异步Ajax文件上传处理

Ajax文件上传处理并返回含图片位置的json对象用于回显图片

//异步Ajax文件上传处理
@ResponseBody
@RequestMapping("/ajaxImg")
//pimage与前台上传的name值一样
public Object ajaxImg(MultipartFile pimage,HttpServletRequest request){
    
    
    //生成文件名和后缀,通过FileNameUtil工具类将前台上传的文件名通过UUID重新生成,防止重复
    String uuidFileName = FileNameUtil.getUUIDFileName()+FileNameUtil.getFileType(pimage.getOriginalFilename());
    //存取路径  -- 完整的项目本地路径
    String path = request.getServletContext().getRealPath("/image_big");
    //存储  File.separator -> \
    try {
    
    
        pimage.transferTo(new File(path+File.separator+uuidFileName));
    } catch (IOException e) {
    
    
        e.printStackTrace();
    }

    //返回josn对象,包含图片路径,
    String s = "{\"imgurl\":\""+uuidFileName+"\"}";
    return s;
}

FileNameUtil工具类 – 用于UUID文件名防止重复

package com.yanyu.utils;

import java.util.UUID;

public class FileNameUtil {
    
    
	//根据UUID生成文件名
	public static String getUUIDFileName() {
    
    
		UUID uuid = UUID.randomUUID();
		return uuid.toString().replace("-", "");
	}
	//从请求头中提取文件名和类型
	public static String getRealFileName(String context) {
    
    
		// Content-Disposition: form-data; name="myfile"; filename="a_left.jpg"
		int index = context.lastIndexOf("=");
		String filename = context.substring(index + 2, context.length() - 1);
		return filename;
	}
	//根据给定的文件名和后缀截取文件名
	public static String getFileType(String fileName){
    
    
		//9527s.jpg
		int index = fileName.lastIndexOf(".");
		return fileName.substring(index);
	}
}

补充 :ajaxfileupload.js


jQuery.extend({
    
    

    createUploadIframe: function(id, uri)
	{
    
    
			//create frame
            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)
	{
    
    
		//create form	
		var formId = 'jUploadForm' + id;
		var fileId = 'jUploadFile' + id;
		var form = $('<form  action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');	
		var oldElement = $('#' + fileElementId);
		var newElement = $(oldElement).clone();
		$(oldElement).attr('id', fileId);
		$(oldElement).before(newElement);
		$(oldElement).appendTo(form);
		//set attributes
		$(form).css('position', 'absolute');
		$(form).css('top', '-1200px');
		$(form).css('left', '-1200px');
		$(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 = s.fileElementId;        
		var form = jQuery.createUploadForm(id, s.fileElementId);
		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 
										{
    
    
											$(io).remove();
											$(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 io = $('#' + frameId);
			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) 
		{
    
    			
            jQuery.handleError(s, xml, null, 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 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("<div>").html(data).evalScripts();
			//alert($('param', data).each(function(){alert($(this).attr('value'));}));
        return data;
    }
})


猜你喜欢

转载自blog.csdn.net/qq_44058265/article/details/120495112