簡體   English   中英

將文件轉換為 Base64

[英]Convert file to Base64

所以我正在嘗試從標簽轉換文件。 這就是我的 javascript 代碼的樣子:

var file = document.getElementById("file").files[0];
if (file) {
  var filereader = new FileReader();
  filereader.readAsDataURL(file);
  filereader.onload = function (evt) {
    var base64 = evt.target.result;
  }
}

那返回undefined

我認為您錯過了代碼中的 return 語句。 將您的 function 替換為以下行:

var file = document.getElementById("file").files[0];
if (file) {
  var filereader = new FileReader();
  filereader.readAsDataURL(file);
  filereader.onload = function (evt) {
     var base64 = evt.target.result;
      return base64
  }

}

兩個小幫手和一個例子。

const blobToDataUrl = blob => new Promise((resolve, reject) => {
  const reader = new FileReader();
  reader.onload = () => resolve(reader.result);
  reader.onerror = reject;
  reader.readAsDataURL(blob);
});

const blobToBase64 = blob => blobToDataUrl(blob).then(text => text.slice(text.indexOf(",")));

for(let file of document.getElementById("file").files) {
  blobToBase64(file).then(base64 => console.log(file, base64));
}

但為什么是承諾?

因為您的下一個問題是: How do I get the base64 string out of onload? 簡短的回答是You don't 一個更長的答案是: It's like asking how to get something from the future into the now. You can't. It's like asking how to get something from the future into the now. You can't.

Promise 是最終可用的值的占位符/包裝器; 但還沒有 它們是異步函數的基礎。

所以讓我們跳過回調的混亂,直接進入你寫的地方

for(let file of document.getElementById("file").files) {
  const base64 = await blobToBase64(file);
  console.log(file, base64);
}

但為此,您將不得不重溫 asyncawait

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM