標題既然寫著實作,這篇就不逐行講解語法了。這個案例是我參考了大約五六款拖曳上傳外掛與 Demo,把各自做得好的地方挑出來整合而成的成果,直接看效果吧(線上網址未必長期有效,若失效請見文末的 Demo 下載)。

介面樣式參考的是一個國外相簿網站,改動不大,主要是把英文換成中文,並調整了上傳時的狀態顯示。之所以選它當基底,是因為擴充性極好:它同時支援三種加入圖片的方式——拖曳上傳、傳統選擇檔案上傳,以及貼上網路圖片網址,而且把三條路徑整合得相當自然。
還有個貼心細節:如果你用不支援 HTML5 的舊版 IE 開啟,拖曳上傳的提示區塊根本不會出現,畫面自動退化為純粹的檔案選擇模式。

拖曳上傳的七成功能都在前端,剩下的三成才是把圖片資訊送到後端做壓縮、裁切等處理。先看 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();
},
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) {
// Chrome 8+
img.src = window.webkitURL.createObjectURL(fileList[0]);
} else if ($.browser.mozilla) {
// FF 4+
img.src = window.URL.createObjectURL(fileList[0]);
} else {
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 與 FormData 三個 API:拖曳事件負責接住檔案、FileReader 或 createObjectURL 負責前端預覽、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) {
$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;
$y_mid = $new_height * .5;
$new = imagecreatetruecolor(round($new_width), round($new_height));
imagecopyresampled($new, $image, 0, 0, 0, 0, $new_width, $new_height, $w, $h);
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);
}
imageinterlace($crop ? $crop : $new, true);
$dext = strtolower(pathinfo($destination, PATHINFO_EXTENSION));
switch ($dext) {
case 'jpeg':
case 'jpg':
imagejpeg($crop ? $crop : $new, $destination, $quality);
break;
case 'png':
$pngQuality = round(abs(($quality - 100) / 11.111111));
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,前端收到後解析並 append 到預覽區,整個流程就完成了。
文章開頭提到的另外兩種方式——點擊選擇檔案、以及新增網路圖片——不在這次主題範圍內,實作難度也不高,這裡就不展開。
不過有兩點值得注意。第一,範例中的 $.browser 在 jQuery 1.9 之後已被移除,新專案請改用 Modernizr 或 window.File && window.FileReader 之類的能力偵測。第二,上傳端點務必做副檔名白名單、MIME 與實際檔案內容的檢驗,並限制檔名格式,單純依賴 $_FILES['type'] 是可以被偽造的。
Demo 下載請見文章原始頁面。