从html文件上传元素获取base64字符串

时间:2015-04-01 04:34:04

标签: javascript html file-upload

我想将图像从文件上传元素转换为base64字符串。

我在这里找到了解决方案 How can you encode a string to Base64 in JavaScript?

@SunnyMilenov答案,但我不知道要传递给函数

 encode : function (input) {...}

2 个答案:

答案 0 :(得分:0)

对HTML5和IE没有HTML5的更新答案

您需要使用FileReader.readAsDataURL()来查看js fiddle示例

function getImage() {

    var reader = new FileReader();
    var f = document.getElementById("file-select").files;

    reader.onloadend = function () {
        console.log(reader.result);
    }
    reader.readAsDataURL(f[0]);

}
<form id="file-form" method="POST">
    <input type="file" id="file-select" />
</form>
<button onclick="getImage()" id="upload-button">Convert</button>

对于没有HTML5的IE ,您需要使用activex对象,并确保允许activex在您的互联网选项中运行脚本

enter image description here

<html>

<head>

<script>

// from http://stackoverflow.com/questions/7370943/retrieving-binary-file-content-using-javascript-base64-encode-it-and-reverse-de
function base64Encode(str) {
    var CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    var out = "", i = 0, len = str.length, c1, c2, c3;
    while (i < len) {
        c1 = str.charCodeAt(i++) & 0xff;
        if (i == len) {
            out += CHARS.charAt(c1 >> 2);
            out += CHARS.charAt((c1 & 0x3) << 4);
            out += "==";
            break;
        }
        c2 = str.charCodeAt(i++);
        if (i == len) {
            out += CHARS.charAt(c1 >> 2);
            out += CHARS.charAt(((c1 & 0x3)<< 4) | ((c2 & 0xF0) >> 4));
            out += CHARS.charAt((c2 & 0xF) << 2);
            out += "=";
            break;
        }
        c3 = str.charCodeAt(i++);
        out += CHARS.charAt(c1 >> 2);
        out += CHARS.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
        out += CHARS.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6));
        out += CHARS.charAt(c3 & 0x3F);
    }
    return out;
}

function readFile(filePath){
    var fso = new ActiveXObject("Scripting.FileSystemObject");
    f = fso.GetFile(filePath);
    var textStream = f.OpenAsTextStream();
    var fileData = base64Encode(textStream.Read(f.size));
    textStream.close();

    return fileData;
}

function getImage() {
    var filePath = document.getElementById("file-select").value;
    var fileData = readFile(filePath);
    document.getElementById("output").value = fileData;
}


</script>


</head>
<body>


<form id="file-form" method="POST">
    <input type="file" id="file-select" />
</form>
<button onclick="getImage()" id="upload-button">Convert</button>

<br>

<textarea id="output" cols="100" rows="20"></textarea>

</body>
</html>

答案 1 :(得分:0)

<!DOCTYPE html>
<html>
<style type="text/css">

</style>
<head>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
    function convertImgToBase64(url, callback, outputFormat){
    var canvas = document.createElement('CANVAS');
    var ctx = canvas.getContext('2d');
    var 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);
          // Clean up
        canvas = null; 
    };
    img.src = url;
  }


  $('#img2b64').submit(function(event){
      var imageUrl = $(this).find('input[name=url]').val();
      console.log('imageUrl', imageUrl);
      convertImgToBase64(imageUrl, function(base64Img){
          $('.output')
              .find('textarea')
                  .val(base64Img)
                  .end()
              .find('a')
                  .attr('href', base64Img)
                  .text(base64Img)
                  .end()
              .find('img')
                  .attr('src', base64Img);
      });

      event.preventDefault();
  });
});
</script>
</head>
<body>
<h2>Input</h2>  
<form class="input-group" id="img2b64">
    <input 
        type="url" 
        name="url" 
        class="form-control"
        placeholder="Insert an IMAGE-URL" 
        value="http://upload.wikimedia.org/wikipedia/commons/4/4a/Logo_2013_Google.png"  
        required>
    <span class="input-group-btn">
        <input 
            type="submit" 
            class="btn btn-default">
    </span>
</form>

<hr>

<h2>Output</h2>        
<div class="output">
    <textarea class="form-control"></textarea><br>
    <a></a><br><br>
    <img><br>
</div>
</body>

</body>
</html>