2016-04-06 78 views
0

我aswer我相信很容易。我需要創建一個代碼來獲取FileReader函數中的base64內容以發送到數據庫。我嘗試將base64字符串放在隱藏的表單類型中,但我無法做到。我上傳波紋管的源代碼:Javascript 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> 
+0

https://jsfiddle.net/41ynj4gc/ – Jaccon

回答

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。而是將結果顯示在ID爲「b64」的spandocument.getElementById('b64').innerHTML = ...
  • 因爲,只能爲1個文件起作用。需要小的編輯或將回document.write,支持多種文件

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