DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> 關於JavaScript >> 圖片上傳判斷及預覽腳本的效果實例
圖片上傳判斷及預覽腳本的效果實例
編輯:關於JavaScript     
復制代碼 代碼如下:
<div id="imgbox">
    <img id="imghead" src="img/no_photo.gif" alt="" width="100" height="125" />
    </div>
<asp:FileUpload ID="FileUploadImg" runat="server" onchange='previewImage(this);'
                            style="position:relative;left:-130px;cursor:pointer;"/>
var $$ = function(id) {
    return "string" == typeof id ? document.getElementById(id) : id;
};
/*
圖片驗證
*/
//驗證上傳圖片格式
function checkupload(ele) {
    var obj = $$("FileUploadImg");
    var fileContentType = obj.value.match(/^(.*)(\.)(.{1,8})$/)[3]; //這個文件類型正則很有用:)   
    if (fileContentType == 'gif' || fileContentType == 'jpeg' || fileContentType == 'png' || fileContentType == 'jpg') {
        //驗證上傳圖片大小
        return checkFileSize(ele);
    } else {
        alert('上傳文件格式不正確!');
        return false;
    }
    return false;
}
//驗證上傳圖片大小
function checkFileSize(ele) {
    var maxSize = 100 * 1024;
    //ie
    if (window.navigator.userAgent.indexOf("MSIE") >= 1) {
        var fso;
        try {
            fso = new ActiveXObject('Scripting.FileSystemObject');
            var file = fso.GetFile(ele.value);
            //alert(file.Size);
            return file.Size < maxSize;
        } catch (e) {
            alert("浏覽器設置禁用ActiveXObject控件,請啟用");
            return false;
        }
    }
    //firefox
    else if (window.navigator.userAgent.indexOf("Firefox") >= 1) {
        //alert(ele.files[0].fileSize);
        return ele.files[0].fileSize < maxSize;
    }
    return false;
}
//加載預覽圖片
function previewImage(ele) {
    if (ele && checkupload(ele)) {
        var imgDiv = $$("imgbox");
        imgDiv.innerHTML = "";
        imgDiv.style.width = "100px";
        imgDiv.style.height = "125px";
        //ie
        if (window.navigator.userAgent.indexOf("MSIE") >= 1) {
            imgDiv.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod = scale)";
            imgDiv.filters("DXImageTransform.Microsoft.AlphaImageLoader").src = ele.value;
        }
        //firefox
        else if (window.navigator.userAgent.indexOf("Firefox") >= 1) {
            imgDiv.innerHTML = "<img width='" + 100 + "' height='" + 125 + "' id='aPic' src='" + ele.files.item(0).getAsDataURL() + "'>";
        } else {
            imgDiv.innerHTML = "<span style='color:red;'>IE/火狐浏覽器才支持圖片預覽</span>";
        }
    } else {
        $$("FileUploadImg").value = "";
        $$("imgbox").innerHTML = "<img id='imghead' src='img/no_photo.gif' alt='' width='100' height='125' />";
        //alert('重置上傳控件');
    }
}
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved