jquery 圖片文件轉base64 顯示


<!DOCTYPE html>  
<html>  
<head>  
    <meta name="viewport" content="width=device-width" />  
    <title>jquery 圖片base64</title>  
    <script type='text/javascript' src="@Url.Content("~/Scripts/jquery-1.10.2.js")"></script>  
</head>  
<body>  
    <div id="testPhone" class="weui_uploader_input_wrp" style="width:79px; height:79px;">  
    </div>  
    <input id="testFile" type="file">  
    <hr>  
    <img id="testImg" style="max-height: 300px; height: 8em; min-width:8em;">  
    <hr>  
    <textarea id="testArea" style="display: block; width: 100%;height: 30em;"></textarea>  
    <input id="btnTest" type="button" value="提交base" />  
    <script>  
        $("#testPhone").click(function () {  
            $("#testFile").click();  
        });  
  
        $("#testFile").change(function () {  
            run(this, function (data) {  
                $('#testImg').attr('src', data);  
                $('#testArea').val(data);  
            });  
        });  
  
        $("#btnTest").click(function () {  
            $.ajax({  
                url: "/usercenter/testbaseaction",  
                type: "post",  
                dataType: "json",  
                data: {  
                    "content": $("#testArea").val(),  
                },  
                async: false,  
                success: function (result) {  
                    if (result.Code == 200) {  
                        alert(result.Data);  
                    } else {  
                    }  
                }  
            });  
        });  
  
        function run(input_file, get_data) {  
            /*input_file:文件按鈕對象*/  
            /*get_data: 轉換成功后執行的方法*/  
            if (typeof (FileReader) === 'undefined') {  
                alert("抱歉,你的瀏覽器不支持 FileReader,不能將圖片轉換為Base64,請使用現代瀏覽器操作!");  
            } else {  
                try {  
                    /*圖片轉Base64 核心代碼*/  
                    var file = input_file.files[0];  
                    //這里我們判斷下類型如果不是圖片就返回 去掉就可以上傳任意文件  
                    if (!/image\/\w+/.test(file.type)) {  
                        alert("請確保文件為圖像類型");  
                        return false;  
                    }  
                    var reader = new FileReader();  
                    reader.onload = function () {  
                        get_data(this.result);  
                    }  
                    reader.readAsDataURL(file);  
                } catch (e) {  
                    alert('圖片轉Base64出錯啦!' + e.toString())  
                }  
            }  
        }  
    </script>  
</body>  
</html>  

 

jquery 圖片base64

 




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM