DIV CSS 佈局教程網

HTML5 多圖片上傳與即時預覽實作解析
編輯:關於JavaScript     

這篇要動手做一個不依賴任何外掛的多圖上傳元件:選檔後立刻看到縮圖預覽,按下上傳還能看到進度。範例刻意不做前端切片,把焦點放在 HTML5 與 XHR 的原生能力上。

用到的四個關鍵技術

1. HTML5 的 files:一次可選多檔,並取得每個檔案的 metadata。
2. XMLHttpRequest:負責送出 HTTP 請求。
3. FormData:把每個檔案分別包裝後傳輸。
4. FileReader.readAsDataURL:把圖片內容直接轉成 data URL,塞進 img 的 src,就能生成預覽。

頁面結構與樣式

<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html" charset="utf-8" />
<title>test html FileReader</title>
<style type="text/css">
html,body,header,footer,div,ul,li,h1,h2,h3,h4,h5,h6,label,input,textarea,p,span,a{
    padding: 0;
    margin: 0;
}
img { border: 0; }
em,strong{ font-weight: normal; font-style: normal; }
ul { list-style: none; }
h1,h2,h3,h4,h5,h6 { font-weight: normal; font-size: 100%; }
a,a:after{ text-decoration:none; }
.photo_wrap{ clear:both; }
.photo_wrap li{ margin:10px; width:150px; float:left; }
.photo_box { height:150px; width:150px; overflow:hidden; position:relative; }
.photo_box .img1{ height:150px; }
.photo_box .img2{ width:150px; }
.upload_result{ height:50px; }
.btns{ position:relative; height:40px; width:100px; float:left; }
.btn{ height:40px; line-height:40px; color:#FFF; display:block; border-radius:3px;
      text-align:center; background-color:#FF5581;
      background-image: linear-gradient(to bottom,#FA7B9C 0%, #FF5581 100%);
      box-shadow:0 1px 0 rgba(255,255,255,0.3) inset, 0 1px 2px rgba(0,0,0,0.3); }
.btn_add_pic{ width:100px; position:absolute; top:0; left:0; }
.btn_upload{ width:100px; margin:0 10px 10px; float:left; }
.btn:hover, .btn_cur{ background-color:#FB99B1; }
.file_input_wrap{ position:absolute; top:0; left:0; width:100px; height:40px; }
.file_input_wrap label{ width:100%; height:100%; display:block; opacity:0; cursor:pointer; }
.file_input_wrap input{ opacity:0; filter:alpha(opacity=0); position:absolute;
                        top:7px; right:173px; cursor:pointer; width:95px; }
.photo_box .icon_pos{ height:20px; width:20px; display:block;
                      position:absolute; right:0; bottom:0; }
.photo_box .loading{ height:10px; display:block; position:absolute; left:0; bottom:0;
                     background-image:url(loading.gif); }
.sucess_icon{ background-image:url(icons_01.png); background-position:0 0; }
.error_icon{ background-image:url(icons_01.png); background-position:-20px 0; }
</style>
</head>
<body>
<div class="btns">
    <a class="btn btn_add_pic" id="J_add_pic" href="javascript:;">添加圖片</a>
    <div class="file_input_wrap">
        <input type="file" id="file" name="file" accept="image/*" multiple onChange="fileInfo(this)" />
        <label id="J_add_area"></label>
    </div>
</div>
<a class="btn btn_upload" id="J_upload" href="javascript:;">開始上傳</a>
<div id="J_photo_wrap">
    <ul class="photo_wrap"></ul>
</div>

核心腳本

<script type="text/javascript" src="jquery-1.7.2.min.js"></script>
<script type="text/javascript">
var img_index = new Array();

function upload_img() {
    var j = 0;
    img();

    function img() {
        if (img_index.length > 0) {
            var singleImg = img_index[j];
            var xmlhttp;
            if (window.XMLHttpRequest) {
                xmlhttp = new XMLHttpRequest();
                if (xmlhttp.overrideMimeType) {
                    xmlhttp.overrideMimeType('text/xml');
                }
            } else if (window.ActiveXObject) {
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }

            if (xmlhttp.upload) {
                // 進度條
                xmlhttp.upload.addEventListener("progress", function (e) {
                    if (e.lengthComputable) {
                        var load_percent = (e.loaded / e.total) * 100;
                        $('#J_photo_wrap ul li').eq(j).find('.loading')
                            .css('width', load_percent + '%');
                    }
                }, false);

                xmlhttp.onreadystatechange = function (e) {
                    if (xmlhttp.readyState == 4) {
                        if (xmlhttp.status == 200) {
                            var json = eval('(' + xmlhttp.responseText + ')');
                            if (json.status == 1) {
                                $('#J_photo_wrap ul li').eq(j).find('.upload_result')
                                    .text(singleImg.name + '上傳完成');
                                $('#J_photo_wrap ul li').eq(j).find('.loading').hide();
                                $('#J_photo_wrap ul li').eq(j).find('.icon_pos')
                                    .addClass('sucess_icon');
                            } else {
                                $('#J_photo_wrap ul li').eq(j).find('.upload_result')
                                    .text(singleImg.name + '上傳失敗');
                                $('#J_photo_wrap ul li').eq(j).find('.loading').hide();
                                $('#J_photo_wrap ul li').eq(j).find('.icon_pos')
                                    .addClass('error_icon');
                            }
                        } else {
                            $('#J_photo_wrap ul li').eq(j).find('.upload_result')
                                .text(singleImg.name + '上傳失敗');
                            $('#J_photo_wrap ul li').eq(j).find('.loading').hide();
                            $('#J_photo_wrap ul li').eq(j).find('.icon_pos')
                                .addClass('error_icon');
                        }
                        if (j < img_index.length - 1) {
                            j++;
                            img(); // 遞迴處理下一張
                        }
                    }
                };

                // open 只初始化參數,不發送請求;第三個參數 true 表示非同步
                xmlhttp.open("POST", "upload.php", true);

                var formdata = new FormData();
                formdata.append("FileData", singleImg);
                xmlhttp.send(formdata);
            }
        }
    }
}

$('#J_upload').click(function () { upload_img(); });

$('#J_add_area').hover(
    function () { $('#J_add_pic').addClass('btn_cur'); },
    function () { $('#J_add_pic').removeClass('btn_cur'); }
);
$('#J_add_area').click(function () { $('#file').click(); });

// 依長寬比決定用哪個 class,避免變形
function resize(img) {
    if (img.offsetHeight > img.offsetWidth) {
        $(img).removeClass('img1').addClass('img2');
    } else {
        $(img).removeClass('img2').addClass('img1');
    }
}

function fileInfo(source) {
    var ireg = /image\/.*/i;
    var files = source.files;
    var name, size, type;
    for (var i = 0, f; f = files[i]; i++) {
        name = f.name;
        size = f.size;
        type = f.type;
        if (!type.match(ireg)) {
            $('#J_photo_wrap ul').append(
                '<li><div class="photo_box">' + name + '不是圖片' +
                '<span class="loading"></span><span class="icon_pos"></span>' +
                '</div><div class="upload_result"></div></li>');
        } else {
            img_index.push(f);
            if (size > 1048576) {
                $('#J_photo_wrap ul').append(
                    '<li><div class="photo_box">' + name + '太大,無法生成預覽' +
                    '<span class="loading"></span><span class="icon_pos"></span>' +
                    '</div><div class="upload_result"></div></li>');
            } else {
                if (window.FileReader) {
                    var fr = new FileReader();
                    fr.onload = (function (f) {
                        return function (e) {
                            $('#J_photo_wrap ul').append(
                                '<li><div class="photo_box">' +
                                '<img onload="resize(this);" src="' + this.result + '"/>' +
                                '<span class="loading"></span><span class="icon_pos"></span>' +
                                '</div><div class="upload_result"></div></li>');
                        };
                    })(f);
                    fr.readAsDataURL(f);
                }
            }
        }
    }
}
</script>
</html>

後端怎麼收

這裡只示範接收,取出檔名、類型與大小後回傳 JSON:

<?php
$name = $_FILES['FileData']['name'];
$type = $_FILES['FileData']['type'];
$size = $_FILES['FileData']['size'];
$return = array(
    "name" => $name,
    "type" => $type,
    "size" => $size,
    "status" => 1
);
echo json_encode($return);
?>

這個做法的兩個罩門

1. readAsDataURL 會把整張圖讀進記憶體再產生縮圖,遇到大檔瀏覽器容易卡住甚至崩潰。
2. 上傳沒有做切片處理,單檔過大時成功率與體驗都會受影響。

要正式上 production,這兩點建議改用 createObjectURL 產生預覽、並搭配分片上傳來解決。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved