html5 ajax多圖片可預覽上傳圖片樣本

來源:互聯網
上載者:User

最近不是特別忙,我就利用html5寫了個上傳圖片(或其他檔案)的頁面,主要利用是html5的file api,此頁面比較簡陋,沒做樣式的最佳化,包含上傳圖片預覽,多圖片上傳,上傳進度條(利用html5的progress標籤做的),上傳網速等,像刪除選中的照片,重新選擇照片,繼續選擇照片等簡單的功能我就沒寫(直接按邏輯修改代碼中的uploadImgArr數組即可),另外可以根據圖片的類型fileType,大小file.size來限制上傳圖片的類型。
PS:由於我的空間流量有限,顧沒有把線上的demo告訴你們,呵呵,如果有需要例子的,可以留言聯絡我。
html5 ajax上傳圖片的代碼如下:

 代碼如下 複製代碼

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>HTML5上傳圖片</title>
<style type="text/css">
li{list-style:none}
li img{width:100px}
.tips{color:red}
</style>
</head>
<body>
<p>注意圖片太小的話,看不到進度條</p>
<input type="file" id="filesInput" multiple />
<br><br>
<a href="javascript:;" id="btnUpload">開始上傳</a>
<p id="info"></p>
<label>讀取進度:</label><progress id="Progress" value="0" max="100"></progress>
<span id="percent"></span>
<p id="uploadSpeed"></p>
<ul id="imageBox"></ul>
<script type="text/javascript">
//定義擷取對象的方法
function $(id) {
    return document.getElementById(id);
}
var filesInput = $("filesInput"),
    info = $("info"),
    imageBox = $("imageBox"),
    btnUpload = $("btnUpload"),
    progress = $("Progress"),
    percent = $("percent"),
    uploadSpeed = $("uploadSpeed");
//定義存放圖片對象的數組
var uploadImgArr = [];
//防止圖片上傳完成後,再點擊上傳按鈕的時候重複上傳圖片
var isUpload = false;
//定義擷取圖片資訊的函數
function getFiles(e) {
    isUpload = false;
    e = e || window.event;
    //擷取file input中的圖片資訊列表
    var files = e.target.files,
    //驗證是否是圖片檔案的正則
    reg = /image/.*/i;
    //console.log(files);
    for (var i = 0,f; f = files[i]; i++) {
        //把這個if判斷去掉後,也能上傳別的檔案
        if (!reg.test(f.type)) {
            imageBox.innerHTML += "<li>你選擇的" + f.name + "檔案不是圖片</li>";
            //跳出迴圈
            continue;
        }
        //console.log(f);
        uploadImgArr.push(f);
        var reader = new FileReader();
        //類似於原生JS實現tab一樣(閉包的方法),參見http://www.css119.com/archives/1418
        reader.onload = (function(file) {
            //擷取圖片相關的資訊
            var fileSize = (file.size / 1024).toFixed(2) + "K",
            fileName = file.name,
            fileType = file.type;
            //console.log(fileName)
            return function(e) {
                //console.log(e.target)
                //擷取圖片的寬高
                var img = new Image();
                img.addEventListener("load", imgLoaded, false);
                img.src = e.target.result;
                function imgLoaded() {
                    imgWidth = img.width;
                    imgHeight = img.height;
                    //圖片載入完成後才能擷取imgWidth和imgHeight
                    imageBox.innerHTML += "<li><img src='" + e.target.result + "' alt='" + fileName + "' title='" + fileName + "'> 圖片名稱是:" + fileName + ";圖片的的大小是:" + fileSize + ";圖片的類型是:" + fileType + ";圖片的尺寸是:" + imgWidth + " X " + imgHeight + "</li>";
                }
            }
        })(f);
        //讀取檔案內容
        reader.readAsDataURL(f);
    }
    //console.log(uploadImgArr);
}
if (window.File && window.FileList && window.FileReader && window.Blob) {
    filesInput.addEventListener("change", getFiles, false);
} else {
    info.innerHTML = "您的瀏覽器不支援HTML5長傳";
    info.className="tips";
}
//開始上傳照片
function uploadFun() {
    var j = 0;
    function fun() {
        if (uploadImgArr.length > 0 && !isUpload) {
            var singleImg = uploadImgArr[j];
            var xhr = new XMLHttpRequest();
            if (xhr.upload) {
                //進度條(見http://www.css119.com/archives/1476)
                xhr.upload.addEventListener("progress",
                function(e) {
                    if (e.lengthComputable) {
                        progress.value = (e.loaded / e.total) * 100;
                        percent.innerHTML = Math.round(e.loaded * 100 / e.total) + "%";
                        //計算網速
                        var nowDate = new Date().getTime();
                        var x = (e.loaded) / 1024;
                        var y = (nowDate - startDate) / 1000;
                        uploadSpeed.innerHTML = "網速:" +(x / y).toFixed(2) + " K/S";
                    } else {
                        percent.innerHTML = "無法計算檔案大小";
                    }
                },
                false);
                // 檔案上傳成功或是失敗
                xhr.onreadystatechange = function(e) {
                    if (xhr.readyState == 4) {
                        if (xhr.status == 200 && eval("(" + xhr.responseText + ")").status == true) {
                            info.innerHTML += singleImg.name + "上傳完成; ";
                            //因為progress事件是按一定時間段返回資料的,所以單獨progress不可能100%的,在這設定傳完後強制設定100%
                            progress.value = 100;
                            percent.innerHTML = "100%";
                            isUpload = true;
                        } else {
                            info.innerHTML += singleImg.name + "上傳失敗; ";
                        }
                        //上傳成功(或者失敗)一張後,再次調用fun函數,類比迴圈
                        if (j < uploadImgArr.length - 1) {
                            j++;
                            isUpload = false;
                            fun();
                        }
                    }
                };
                var formdata = new FormData();
                formdata.append("FileData", singleImg);
                // 開始上傳
                xhr.open("POST", "upload.php", true);
                xhr.send(formdata);
                var startDate = new Date().getTime();
            }
        }
    }
    fun();
}
btnUpload.addEventListener("click", uploadFun, false);
</script>
</body>
</html>

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.