简体   繁体   中英

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.

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

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

gives me an output as

data:application/octet-stream;base64,c2hpZWxkLnBuZw== here

I want base64 information, but noticing the file the application/octet-stream is wrong? I entered an image so shouldn't it be

data:image/pgn;base64,c2hpZWxkLnBuZw==

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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