简体   繁体   English

Reactjs - 无法对来自 react-dropzone 的文件进行 base64 编码

[英]Reactjs - Can't base64 encode file from react-dropzone

I am using react-dropzone to handle file upload on my website.我正在使用react-dropzone处理我网站上的文件上传。 When successfully loading a file, the dropzone triggers the following callback:成功加载文件后,dropzone 会触发以下回调:

onDrop: function (acceptedFiles, rejectedFiles) {
  myFile = acceptedFiles[0];
  console.log('Accepted files: ', myFile);
}

I would like to base64 encode this file.我想对这个文件进行 base64 编码。 When doing :做的时候:

var base64data = Base64.encode(myFile)
console.log("base64 data: ", base64data) // => base64 data: W29iamVjdCBGaWxlXQ==W29iamVjdCBGaWxlXQ==

Regardless of file uploaded, it always prints out the same string.无论文件上传,它总是打印出相同的字符串。

Am I missing something ?我错过了什么吗? I need to base64 encode this file (always images)我需要对这个文件进行 base64 编码(总是图像)

This JS Bin is a working example of converting a File to base64: http://jsbin.com/piqiqecuxo/1/edit?js,console,output .这个 JS Bin 是一个将文件转换为 base64 的工作示例: http : //jsbin.com/piqiqecuxo/1/edit ?js,console, output The main addition seems to be reading the file using a FileReader , where FileReader.readAsDataURL() returns a base64 encoded string主要的补充似乎是使用FileReader读取文件,其中FileReader.readAsDataURL()返回一个 base64 编码的字符串

document.getElementById('button').addEventListener('click', function() {
  var files = document.getElementById('file').files;
  if (files.length > 0) {
    getBase64(files[0]);
  }
});

function getBase64(file) {
   var reader = new FileReader();
   reader.readAsDataURL(file);
   reader.onload = function () {
     console.log(reader.result);
   };
   reader.onerror = function (error) {
     console.log('Error: ', error);
   };
}

If you want it in a neat method that works with async / await, you can do it this way如果您希望以一种适用于 async/await 的简洁方法来实现它,您可以这样做

const getBase64 = async (file: Blob): Promise<string | undefined> => {
  var reader = new FileReader();
  reader.readAsDataURL(file as Blob);

  return new Promise((reslove, reject) => {
    reader.onload = () => reslove(reader.result as any);
    reader.onerror = (error) => reject(error);
  })
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM