ajaxFileUpload+springMvcマルチファイルアップロード

8331 ワード

1.xml構成

<bean id="multipartResolver"  
    class="org.springframework.web.multipart.commons.CommonsMultipartResolver" >  
    <!-- set the max upload size1MB   1048576     -->  
    <property name="maxUploadSize">  
        <value>52428800</value>  
    </property>  
    <property name="maxInMemorySize">  
        <value>2048</value>  
    </property>  
</bean>

2.バックエンド

@RequestMapping("/wxupload.html")
	public String upload(MultipartHttpServletRequest multipartRequest,
			HttpServletResponse response,ModelMap model) throws Exception{
		AppointmentVo appointment = (AppointmentVo) this.getSessionObject(multipartRequest, "appointment");
		if(appointment == null){
			model.put("result", "0");
			//return "front/success";
			this.writerResponse(response, "0");
			return null;
		}
//		String frontIdCardInfoName=(String) multipartRequest.getFileNames().next();
//		String backIdCardInfoName=(String) multipartRequest.getFileNames().;
		int i=0;
		String path = loader.getProperty("pang.upload");
		String customerId = appointment.getCustomerId();
		AppointCustomer ac = new AppointCustomer();
		ac.setCustomerId(customerId);
		for (Iterator it = multipartRequest.getFileNames(); it.hasNext();) {  
			String key = (String) it.next();  
	        MultipartFile imgFile = multipartRequest.getFile(key);
	        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSS");
			String frontName = Utils.getFileName(imgFile.getOriginalFilename());
			String frontType = Utils.getFileType(imgFile.getOriginalFilename());
			String frontIdCardInfoName = frontName +"_"+ sdf.format(new Date())+frontType;
			File frontTargetFile = new File(path+"/"+frontIdCardInfoName);
			if(!frontTargetFile.exists()){
				frontTargetFile.mkdirs();
			}
			imgFile.transferTo(frontTargetFile);// 
	        if(i==0)
	        {
	        	ac.setFrontIdCardInfo(path+"/"+frontIdCardInfoName);
	        	
	        }else
	        {
	        	ac.setBackIdCardInfo(path+"/"+frontIdCardInfoName);
	        }
	        i++;
	      
		}
			try{
				this.appointCustomerService.update(ac);
				model.put("message", " ");
				this.writerResponse(response, "2");
			}catch(Exception e){
				model.put("message", " ");
				this.writerResponse(response, "1");
				e.printStackTrace();
			}
		return null;
		//return "front/success";
	}

3.ajaxFileUploadFileを修正する.jsのソースコード
ソースファイルのcreateUploadFormのコードを次のように置き換えます.

    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) {  
                        jQuery(  
                                '<input type="hidden" name="' + i + '" value="'  
                                        + data[i] + '" />').appendTo(form);  
                    }  
                }  
                for (var i = 0; i < fileElementId.length; i ++) {  
                    var oldElement = jQuery('#' + fileElementId[i]);  
                    var newElement = jQuery(oldElement).clone();  
                    jQuery(oldElement).attr('id', fileElementId[i]);  
                    jQuery(oldElement).attr('name', fileElementId[i]);  
                    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;  
            }  

4.ここではパッケージクラスを専門に書くことができ、fileにonchangeイベント判定ファイルフォーマットを追加することができます.時間が限られているため、変更されていません

[javascript] view plaincopyprint?

    var count = 1;  
    /** 
    *   
    */  
    function createInput(parentId){  
        count++;  
        var str = '<div name="div" ><font style="font-size:12px;"> </font>'+  
        '   '+ '<input type="file" contentEditable="false" id="uploads' + count + '' +  
        '" name="uploads'+ count +'" value="" style="width: 220px"/><input type="button"  value=" " onclick="removeInput(event)" />'+'</div>';  
        document.getElementById(parentId).insertAdjacentHTML("beforeEnd",str);  
    }  
    /** 
    *   
    */  
    function removeInput(evt, parentId){  
       var el = evt.target == null ? evt.srcElement : evt.target;  
       var div = el.parentNode;  
       var cont = document.getElementById(parentId);         
       if(cont.removeChild(div) == null){  
        return false;  
       }  
       return true;  
    } 

5.次は2つの修正用のjsで、表示と削除のために使用され、上の合成簡略コードで使用できます.

[javascript] view plaincopyprint?

    function addOldFile(data){  
        var str = '<div name="div' + data.name + '" ><a href="#" style="text-decoration:none;font-size:12px;color:red;" onclick="removeOldFile(event,' + data.id + ')"> </a>'+  
        '   ' + data.name +   
        '</div>';  
        document.getElementById('oldImg').innerHTML += str;  
    }  
      
    function removeOldFile(evt, id){  
        // , file ,   
        $("#imgIds").val($("#imgIds").val()=="" ? id :($("#imgIds").val() + "," + id));  
        var el = evt.target == null ? evt.srcElement : evt.target;  
        var div = el.parentNode;  
        var cont = document.getElementById('oldImg');      
        if(cont.removeChild(div) == null){  
            return false;  
        }  
        return true;  
    }  

6.ajaxアップロードファイル:

[javascript] view plaincopyprint?

    function ajaxFileUploadImg(id){  
            // file id  
            var uplist = $("input[name^=uploads]");  
        var arrId = [];  
        for (var i=0; i< uplist.length; i++){  
            if(uplist[i].value){  
                arrId[i] = uplist[i].id;  
            }  
            }  
        $.ajaxFileUpload({  
            url:'xxxxx',  
            secureuri:false,  
            fileElementId: arrId,  // id , !  
            dataType: 'json',  
            data: {  
                         //   
                    },  
            success: function (data){  
            },  
            error: function(data){  
            }  
        });  
    }