简体   繁体   中英

convert PDF file using path to Base64 String in Javascript

I'm trying to pass the path from the function for get the binary file base64 String, as like below.

 var file = 'dir/file.pdf'; 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); }; } 

But as it returning me undefined

i need similar like this

data:application/pdf;base64,JVBERi0xLjUKJdDUxdgKNSAws2...

How this can be done?

With fileReader you can convert your file from path like this :

var file = new File("/pdf/test.pdf","r");

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);
   };
}

The solution of Lèo is good, except that it is necessary to use the good arguments for the constructor's file. Example :

var file = new File(["foo"], "/pdf/test.pdf", {type: 'application/pdf'});

Here the documentation of the Api: File mdn

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