Javascript base64 convertion

时间:2016-04-06 07:36:36

标签: javascript filereader

我的aswer我相信很容易。我需要创建一个代码来获取FileReader函数中的base64内容以发送到数据库。我尝试将base64字符串放入表单类型隐藏但我不能这样做。我上传源代码:

JSFIDDLE

<script type="text/javascript">
  function readMultipleFiles(evt) {
    //Retrieve all the files from the FileList object
    var files = evt.target.files; 

    if (files) {
        for (var i=0, f; f=files[i]; i++) {
              var r = new FileReader();
            r.onload = (function(f) {
                return function(e) {
                    var contents = e.target.result;
                    alert( 
                          "name: " + f.name + "n"
                          + "starts with: " + contents.substr(1, contents.indexOf("n"))
                    ); 
                    document.write(f.name);
                };
            })(f);

            r.readAsText(f);
        }   
    } else {
          alert("Failed to load files"); 
    }
  }

  document.getElementById('fileinput').addEventListener('change', readMultipleFiles, false);
</script>

1 个答案:

答案 0 :(得分:0)

尝试使用MDN中的函数,该函数也应该支持unicode:

function readMultipleFiles(evt) {
    //Retrieve all the files from the FileList object
    var files = evt.target.files; 

    if (files) {
        for (var i=0, f; f=files[i]; i++) {
              var r = new FileReader();
              r.onload = (function(f) {
                return function(e) {
                    var contents = e.target.result;
                    alert( 
                          "name: " + f.name + "n"
                          + "starts with: " + contents.substr(1, contents.indexOf("n"))
                    ); 
                    document.getElementById('b64').innerHTML = b64EncodeUnicode(contents);
                };
            })(f);

            r.readAsText(f);
        }   
    } else {
          alert("Failed to load files"); 
    }
}

document.getElementById('fileinput').addEventListener('change',
                                          readMultipleFiles, false);
function b64EncodeUnicode(str) {
    return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, 
              function(match, p1) {
                  return String.fromCharCode('0x' + p1);
              }));
}

注意:

  • 我使用ascii文件和https://www.base64encode.org/
  • 测试了上述内容
  • 删除了document.write。而是将结果显示在span中,ID =&#34; b64&#34; (document.getElementById('b64').innerHTML = ...
  • 按原样,仅适用于1个文件。需要进行轻微编辑或放回document.write以支持多个文件

小提琴:https://jsfiddle.net/g6g1a51p/4/