HTML5 拖拽上傳圖片實例


  因為標題寫的是實例,所以本次就不做講解了,因為這個實例我也算是東拼西湊整出來的,參考了大概5、6款拖拽上傳的插件和demo,然后把其中好的地方挑出來,最后就成了這么一個實例,一起來看下吧(地址不能保證長久有效,如果失效請在文章最后點擊demo下載):http://hoorayos.caifutang.com/dropupload.html

  界面樣式我是參考了一個國外的相冊網站,改動不大,只是把鳥語轉換成中文,以及上傳時的樣式也進行了改動,之所以選這個的原因就是,我很容易做擴展,它支持3種方式添加圖片,一種拖拽上傳,一種常規的選擇文件上傳,另外的就是添加網絡圖片。它很巧妙的把三種上傳模式整合到了一起,而且你可以用IE瀏覽器瀏覽下,如果不支持HTML5,是沒有拖拽上傳圖片的提示的,如圖:

  拖拽上傳最重要的就是js部分的代碼,它實現了70%的功能,另外30%僅僅是把圖片信息提交到后台,然后做對應的處理,比如壓縮啊,裁剪啊雲雲。所以先來看下js實現代碼吧。

$().ready(function(){
	if($.browser.safari || $.browser.mozilla){
		$('#dtb-msg1 .compatible').show();
		$('#dtb-msg1 .notcompatible').hide();
		$('#drop_zone_home').hover(function(){
			$(this).children('p').stop().animate({top:'0px'},200);
		},function(){
			$(this).children('p').stop().animate({top:'-44px'},200);
		});
		//功能實現
		$(document).on({
			dragleave:function(e){
				e.preventDefault();
				$('.dashboard_target_box').removeClass('over');
			},
			drop:function(e){
				e.preventDefault();
				//$('.dashboard_target_box').removeClass('over');
			},
			dragenter:function(e){
				e.preventDefault();
				$('.dashboard_target_box').addClass('over');
			},
			dragover:function(e){
				e.preventDefault();
				$('.dashboard_target_box').addClass('over');
			}
		});
		var box = document.getElementById('target_box');
		box.addEventListener("drop",function(e){
			e.preventDefault();
			//獲取文件列表
			var fileList = e.dataTransfer.files;
			var img = document.createElement('img');
			//檢測是否是拖拽文件到頁面的操作
			if(fileList.length == 0){
				$('.dashboard_target_box').removeClass('over');
				return;
			}
			//檢測文件是不是圖片
			if(fileList[0].type.indexOf('image') === -1){
				$('.dashboard_target_box').removeClass('over');
				return;
			}
			
			if($.browser.safari){
				//Chrome8+
				img.src = window.webkitURL.createObjectURL(fileList[0]);
			}else if($.browser.mozilla){
				//FF4+
				img.src = window.URL.createObjectURL(fileList[0]);
			}else{
				//實例化file reader對象
				var reader = new FileReader();
				reader.onload = function(e){
					img.src = this.result;
					$(document.body).appendChild(img);
				}
				reader.readAsDataURL(fileList[0]);
			}
			var xhr = new XMLHttpRequest();
			xhr.open("post", "test.php", true);
			xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
			xhr.upload.addEventListener("progress", function(e){
				$("#dtb-msg3").hide();
				$("#dtb-msg4 span").show();
				$("#dtb-msg4").children('span').eq(1).css({width:'0px'});
				$('.show').html('');
				if(e.lengthComputable){
					var loaded = Math.ceil((e.loaded / e.total) * 100);
					$("#dtb-msg4").children('span').eq(1).css({width:(loaded*2)+'px'});
				}
			}, false);
			xhr.addEventListener("load", function(e){
				$('.dashboard_target_box').removeClass('over');
				$("#dtb-msg3").show();
				$("#dtb-msg4 span").hide();
				var result = jQuery.parseJSON(e.target.responseText);
				alert(result.filename);
				$('.show').append(result.img);
			}, false);
			
			var fd = new FormData();
			fd.append('xfile', fileList[0]);
			xhr.send(fd);
		},false);
	}else{
		$('#dtb-msg1 .compatible').hide();
		$('#dtb-msg1 .notcompatible').show();
	}
});

  開始我是先判斷瀏覽器類型,因為剛才介紹過,不同瀏覽器看到的是不同界面。主要實現代碼是從“功能實現”開始的,這塊具體為何這樣操作,原理是什么,我就不多說了,大家可以參考下這篇文章:《人人網首頁拖拽上傳詳解(HTML5 Drag&Drop、FileReader API、formdata)》,不過ajax上傳部分的代碼還是有點不一樣的,因為人人那個似乎有點麻煩,我就另尋途徑了。

  最后就是上傳部分的PHP代碼了,這里我只是提供個參考,你可以根據項目的需求來自己編寫。

	$r = new stdClass();
	header('content-type: application/json');
	$maxsize = 10; //Mb
	if($_FILES['xfile']['size'] > ($maxsize * 1048576)){
		$r->error = "圖片大小不超過 $maxsize MB";
	}
	$folder = 'files/';
	if(!is_dir($folder)){
		mkdir($folder);
	}
	$folder .= $_POST['folder'] ? $_POST['folder'] . '/' : '';
	if(!is_dir($folder)){
		mkdir($folder);
	}
	
	if(preg_match('/image/i', $_FILES['xfile']['type'])){
	    $filename = $_POST['value'] ? $_POST['value'] : $folder . sha1(@microtime() . '-' . $_FILES['xfile']['name']) . '.jpg';
	}else{
	    $tld = split(',', $_FILES['xfile']['name']);
	    $tld = $tld[count($tld) - 1];
	    $filename = $_POST['value'] ? $_POST['value'] : $folder . sha1(@microtime() . '-' . $_FILES['xfile']['name']) . $tld;
	}
	
	$types = Array('image/png', 'image/gif', 'image/jpeg');
	if(in_array($_FILES['xfile']['type'], $types)){
		$source = file_get_contents($_FILES["xfile"]["tmp_name"]);
		imageresize($source, $filename, $_POST['width'], $_POST['height'], $_POST['crop'], $_POST['quality']);
	}else{
		move_uploaded_file($_FILES["xfile"]["tmp_name"], $filename);
	}
	
	$path = str_replace('test.php', '', $_SERVER['SCRIPT_NAME']);
	
	$r->filename = $filename;
	$r->path = $path;
	$r->img = '<img src="' . $path . $filename . '" alt="image" />';
	
	echo json_encode($r);
	
	function imageresize($source, $destination, $width = 0, $height = 0, $crop = false, $quality = 80) {
	    $quality = $quality ? $quality : 80;
	    $image = imagecreatefromstring($source);
	    if ($image) {
	        // Get dimensions
	        $w = imagesx($image);
	        $h = imagesy($image);
	        if (($width && $w > $width) || ($height && $h > $height)) {
	            $ratio = $w / $h;
	            if (($ratio >= 1 || $height == 0) && $width && !$crop) {
	                $new_height = $width / $ratio;
	                $new_width = $width;
	            } elseif ($crop && $ratio <= ($width / $height)) {
	                $new_height = $width / $ratio;
	                $new_width = $width;
	            } else {
	                $new_width = $height * $ratio;
	                $new_height = $height;
	            }
	        } else {
	            $new_width = $w;
	            $new_height = $h;
	        }
	        $x_mid = $new_width * .5;  //horizontal middle
	        $y_mid = $new_height * .5; //vertical middle
	        // Resample
	        error_log('height: ' . $new_height . ' - width: ' . $new_width);
	        $new = imagecreatetruecolor(round($new_width), round($new_height));
	        imagecopyresampled($new, $image, 0, 0, 0, 0, $new_width, $new_height, $w, $h);
	        // Crop
	        if ($crop) {
	            $crop = imagecreatetruecolor($width ? $width : $new_width, $height ? $height : $new_height);
	            imagecopyresampled($crop, $new, 0, 0, ($x_mid - ($width * .5)), 0, $width, $height, $width, $height);
	            //($y_mid - ($height * .5))
	        }
	        // Output
	        // Enable interlancing [for progressive JPEG]
	        imageinterlace($crop ? $crop : $new, true);
	
	        $dext = strtolower(pathinfo($destination, PATHINFO_EXTENSION));
	        if ($dext == '') {
	            $dext = $ext;
	            $destination .= '.' . $ext;
	        }
	        switch ($dext) {
	            case 'jpeg':
	            case 'jpg':
	                imagejpeg($crop ? $crop : $new, $destination, $quality);
	                break;
	            case 'png':
	                $pngQuality = ($quality - 100) / 11.111111;
	                $pngQuality = round(abs($pngQuality));
	                imagepng($crop ? $crop : $new, $destination, $pngQuality);
	                break;
	            case 'gif':
	                imagegif($crop ? $crop : $new, $destination);
	                break;
	        }
	        @imagedestroy($image);
	        @imagedestroy($new);
	        @imagedestroy($crop);
	    }
	}

  PHP最終會返回一個JSON格式的數組,我返回的信息就是圖片地址、名稱,還有段img的html代碼,最后在js那邊獲取到json數組並處理,至此,操作結束。

  文章最開始提到,還有點擊選擇文件上傳和網絡圖片,因為這2個不屬於這次的主題范圍內,就不說了。況且這2個功能實現起來都不麻煩。

  demo下載


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM