简体   繁体   English

如何将图像转换为 reactJS 中的 base64

[英]How would I convert an image to base64 in reactJS

I have this function where I call a function and have a local file as the parameter to convert it to base64.我有这个 function 我称之为 function 并有一个本地文件作为参数将其转换为 base64。

export const fileToBase64 = (filename, filepath) => {
  return new Promise(resolve => {
    var file = new File([filename], filepath);
    var reader = new FileReader();
    // Read file content on file loaded event
    reader.onload = function(event) {
      resolve(event.target.result);
    };

    // Convert data to base64
    reader.readAsDataURL(file);
  });
}

Importing the function导入 function

  fileToBase64("shield.png", "./form").then(result => {
      console.log(result);
      console.log("here");
    });  

gives me an output as给我一个 output 作为

data:application/octet-stream;base64,c2hpZWxkLnBuZw== here数据:应用程序/八位字节流;base64,c2hpZWxkLnBuZw== 这里

I want base64 information, but noticing the file the application/octet-stream is wrong?我想要 base64 信息,但注意到文件 application/octet-stream 错误? I entered an image so shouldn't it be我输入了一个图像,所以不应该是

data:image/pgn;base64,c2hpZWxkLnBuZw==数据:图像/pgn;base64,c2hpZWxkLnBuZw==

https://medium.com/@simmibadhan/converting-file-to-base64-on-javascript-client-side-b2dfdfed75f6 https://medium.com/@simmibadhan/converting-file-to-base64-on-javascript-client-side-b2dfdfed75f6

try this I think this should helpfull试试这个我认为这应该有帮助

let buff = new Buffer(result, 'base64');
let text = buff.toString('ascii');
console.log(text)

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

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