jquery圖片上傳預(yù)覽

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title></title>
    <script src="https://cdn.bootcss.com/jquery/2.2.4/jquery.min.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:文件按鈕對(duì)象*/
            /*get_data: 轉(zhuǎn)換成功后執(zhí)行的方法*/
            if(typeof(FileReader) === 'undefined') {
                alert("抱歉,你的瀏覽器不支持 FileReader,不能將圖片轉(zhuǎn)換為Base64,請(qǐng)使用現(xiàn)代瀏覽器操作!");
            } else {
                try {
                    /*圖片轉(zhuǎn)Base64 核心代碼*/
                    var file = input_file.files[0];
                    //這里我們判斷下類型如果不是圖片就返回 去掉就可以上傳任意文件  
                    if(!/image\/\w+/.test(file.type)) {
                        alert("請(qǐng)確保文件為圖像類型");
                        return false;
                    }
                    var reader = new FileReader();
                    reader.onload = function() {
                        get_data(this.result);
                    }
                    reader.readAsDataURL(file);
                } catch(e) {
                    alert('圖片轉(zhuǎn)Base64出錯(cuò)啦!' + e.toString())
                }
            }
        }
    </script>
</body>

</html>

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容