JS input file 轉base64 JS圖片預覽

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>簡單的html5 File測試 for pic2base64</title>
<style>
</style>
<script>
    window.onload = function () {
        var input = document.getElementById("fielinput");
        var txshow = document.getElementById("txshow");
        if (typeof (FileReader) === 'undefined') {
            result.innerHTML = "抱歉,你的瀏覽器不支持 FileReader,請使用現代瀏覽器操做!";
            input.setAttribute('disabled', 'disabled');
        } else {
            input.addEventListener('change', readFile, false);
            txshow.onclick = function () { input.click(); }
        }


    }
    function readFile() {
        var file = this.files[0];
        //判斷是不是圖片類型
        if (!/image\/\w+/.test(file.type)) {
            alert("只能選擇圖片");
            return false;
        }
        var reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = function (e) { txshow.src = this.result; alert(this.result); }

    
    }

</script>
</head>
<body>

<input type="file" id="fielinput" >
<img id="txshow" style="width:100px;height:100px;"/>
</body>
</html>html

相關文章
相關標籤/搜索