jquery 图片转为base64

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width" />
    <title>jquery 图片base64</title>
    <script type="text/javascript" src="http://s28.9956.cn/static/v4/js/jquery-1.8.3.min.js"></script>
</head>
<body>
    <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>

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值