天天看點

struts2 +jquey uploadify3.2 實作多檔案上傳,可預覽、删除、排序

源碼下載下傳位址:http://download.csdn.net/detail/ht99582/6276953

struts2 +jquey uploadify3.2 實作多檔案上傳,可預覽、删除、排序

js 代碼

<script type="text/javascript">

      $(function() {
    	  $( "#pics" ).sortable();
  		  //$( ".wraps" ).disableSelection();
    		$("#uploadFile").uploadify({
    			height        : 30,
    			swf           : '${baseURL}/themes/default/images/uploadify.swf',
    			uploader      : '${baseURL}/movieMan/movieManAction!upload.action?savePath=upload',
    			width         : 120,
    			fileObjName:'uploadify',
    			'auto' : false,
    			'buttonText'     : '選擇檔案' ,
    			'multi': true,
    			 'queueID'  : 'some_file_queue',
    			//允許上傳的檔案字尾
    		        'fileTypeExts':'*.jpg;*.jpge;*.gif;*.png',
    		        //上傳檔案的大小限制
    		        'fileSizeLimit':'1MB',
    		        //上傳數量
    		        'queueSizeLimit' : 5,
    			 'onUploadSuccess' : function(file, data, response) {
    				 //$.parseJSON(json)
    		         // alert('The file ' + file.name + ' was successfully uploaded with a response of ' + response + ':' + data);
    				 var html = "<li><div style='position: relative;'> <img src=${baseURL}/"+data+" name='mvUrl' width='100px' height='80px' class='myimg'/><div class='del ui-icon-closethick ui-icon' >删除</div></div></li>";
    				 $("#pics").append(html);
    		        },
    		        'onFallback':function(){
    		            alert("您未安裝FLASH控件,無法上傳圖檔!請安裝FLASH控件後再試。");
    		        },
    		        onSelectError:function(file, errorCode, errorMsg){

                        switch(errorCode) {

                            case -100:

                                alert("上傳的檔案數量已經超出系統限制的"+$('#uploadFile').uploadify('settings','queueSizeLimit')+"個檔案!");

                                break;

                            case -110:

                                alert("檔案 ["+file.name+"] 大小超出系統限制的"+$('#uploadFile').uploadify('settings','fileSizeLimit')+"大小!");

                                break;

                            case -120:

                                alert("檔案 ["+file.name+"] 大小異常!");

                                break;

                            case -130:

                                alert("檔案 ["+file.name+"] 類型不正确!");

                                break;

                        }

                    }
    		});
    		
    	
    		$(".del").die().live('click',function(){
    			$(this).parent().parent().remove();
    		});
    		$(".preview").live({ mouseenter: function () {
    			var src = $(this).parent().find("input").val();
    			src = "${baseURL}/"+src;
    		    $("#testimg").attr("src",src);
    		    var left = $(this).position().left;
    		    var top = $(this).position().top;
    		    $("#imgf").css({left:left,top:top});
    			$("#imgf").show();          
            }, mouseleave: function () {
            	$("#imgf").hide();     
            }
        });
    	});
      
    function dosubmint(){
         $(".mvurl").remove();
         $(".myimg").each(function(){
        	var 	d=$(this).attr("src");
        	d = d.replace('${baseURL}/',"");
        	d = "<input type='hidden' name='mvUrl' class='mvurl' value="+d+">";
        	$("#form1").append(d);
        });
         $("#form1").ajaxSubmit({  
             type: 'post',  
             dataType: 'json', 
             success: function(data){  
                 alert(data.desc);  
             },  
             error: function(XmlHttpRequest, textStatus, errorThrown){  
                 alert( "error");  
             }  
         });   
    }
</script>
           

html 代碼

body {
	font-size: 12px;
}

.wraps {
	clear: both; 
}

.wraps input {
	width: 300px
}

.preview,.del {
	cursor: pointer;
	text-indent: -99999px;
	float: left;
	margin-left: 20px
}
.del{position: absolute;top: 0;right: 0;background-color: white;}
ul li{list-style: none}
#pics{padding: 10px;border: 1px solid #ccc;height: 200px}
#pics li{float: left;display: block;width: 100px;height: 80px;padding: 2px;border: 1px solid #ccc; margin: 10px;}
</style>
<body>
	<div id="some_file_queue"></div>
	<div id="imgf" style="display: none; position: absolute; z-index: 9999">
		<img id="testimg">
	</div>
	<input type="file" name="uploadifys" id="uploadFile" />
	<br />
	<form action="${baseURL}/movieMan/movieManAction!savepics.action?id=${param.id}&fileUrlType=0" id="form1"  dataSrc="${baseURL}/movieMan/movieManAction!getPics.action?id=${param.id}&fileUrlType=0">
	
	<ul id="pics" >
	<!--  
		<li class='wraps' name="list"><input type='text' name='mvUrl'  style='float: left;' /><span class='preview ui-icon ui-icon-newwin' >預覽</span><span class='del ui-icon-closethick ui-icon'>删除</span></li>
	-->
	<li name="list">
		<div style="position: relative;">
		    <img src="${baseURL }/" name="mvUrl" width="100px" height="80px" class="myimg"/>
			<div class='del ui-icon-closethick ui-icon' style="position: absolute;top: 0;right: 0;background-color: white;">删除</div>
		</div>
	</li>
	
	</ul>
	</form>
	<div style="clear: both;margin-top: 20px">

		<button class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-icon-primary" οnclick="javascript:$('#uploadFile').uploadify('upload','*')">
			<span class="ui-button-icon-primary ui-icon ui-icon-play"></span> <span class="ui-button-text">開始上傳</span>
		</button>

		<button class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-icon-primary" οnclick="javascript:$('#uploadFile').uploadify('cancel','*')">
			<span class="ui-button-icon-primary ui-icon ui-icon-cancel"></span> <span class="ui-button-text">取消上傳</span>
		</button>

		<button class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-icon-primary" οnclick="dosubmint()">
			<span class="ui-button-icon-primary ui-icon ui-icon-locked"></span> <span class="ui-button-text">儲存送出</span>
		</button>
	</div>
	

</body>
           

struts action 代碼

private List<File> uploadify;  //對應js裡面的fileObjName,而不是input type ="text" 裡面的name值
    private List<String> uploadifyFileName; 
    private String savePath;//檔案上傳後儲存的路徑
    private List<String> mvUrl;
    private Integer fileUrlType;
           

以上屬性需提供geter,setter 方法

public void upload() throws Exception {  
        File dir=new File(getSavePath());  
        if(!dir.exists()){  
            dir.mkdirs();  
        }  
        List<String> mfiles = new ArrayList<String>();
        for(int i=0;i<uploadify.size();i++){
        	String fileName = DateUtil.format(new Date(), "yyyyMMddHHmmss")+"_"+uploadifyFileName.get(i);
        	 String dest = getSavePath()+"/"+fileName;
        	FileUtils.copyFile(uploadify.get(i), new File(dest));
        	mfiles.add(savePath+"/"+fileName);
        }
        HttpServletResponse response = ServletActionContext.getResponse();
        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        out.write(mfiles.get(0));
        out.close();
        out.flush();
    }