jsローカルプレビュー画像とbase 64

11588 ワード

コードで話す:
<html>
<head>
    <meta charset="UTF-8">
    <title>title>
    <script type="text/javascript">
        function getFileUrl(sourceId) {
            var url;
            if (navigator.userAgent.indexOf("MSIE")>=1) { // IE
                url = document.getElementById(sourceId).value;
            } else if(navigator.userAgent.indexOf("Firefox")>0) { // Firefox
                url = window.URL.createObjectURL(document.getElementById(sourceId).files.item(0));
            } else if(navigator.userAgent.indexOf("Chrome")>0) { // Chrome
                url = window.URL.createObjectURL(document.getElementById(sourceId).files.item(0));
            }
            return url;
        }


        function convertImgToBase64(url, callback, outputFormat){
            var canvas = document.createElement('CANVAS'),
                    ctx = canvas.getContext('2d'),
                    img = new Image;
            img.crossOrigin = 'Anonymous';
            img.onload = function(){
                canvas.height = img.height;
                canvas.width = img.width;
                ctx.drawImage(img,0,0);
                var dataURL = canvas.toDataURL(outputFormat || 'image/png');
                callback.call(this, dataURL);
                canvas = null;
            };
            img.src = url;
        }

        /*
        convertImgToBase64('http://bit.ly/18g0VNp', function(base64Img){
            // Base64DataURL
        });
        */

    script>
head>
<body>
<img width="100" height="100" id="myimg">
<input type="file" id="myfile" >
<input type="button" id="submit" value="  ">


<script type="text/javascript">

    (function() {
                document.querySelector("#myfile").onchange = function(){
                    console.log(this.value);
                    document.querySelector("#myimg").src = getFileUrl(this.id);

                };

                document.querySelector("#submit").onclick = function(){
                    var fsrc;
                    fsrc = getFileUrl("myfile");
                    convertImgToBase64(fsrc, function(base64Img){
                        console.log('11111111111111111');
                        //console.log(base64Img);
                        // Base64DataURL
                    });
                };
            }
    )();
script>

body>
html>
上のコードをファイルに保存してください.
気になるのは
window.URL          sd 

window.URL.createObjectURL             http     。                 。