Try this :-
<input id="inputFile" type="file" onchange="convertToBase64();" />
<script type="text/javascript">
function convertToBase64() {
//Read File
var selectedFile = document.getElementById("inputFile").files;
//Check File is not Empty
if (selectedFile.length > 0) {
// Select the very first file from list
var fileToLoad = selectedFile[0];
// FileReader function for read the file.
var fileReader = new FileReader();
var base64;
// Onload of file read the file content
fileReader.onload = function(fileLoadedEvent) {
base64 = fileLoadedEvent.target.result;
// Print data in console
console.log(base64);
};
// Convert data to base64
fileReader.readAsDataURL(fileToLoad);
}
}
</script>
Answer from Mohit Singh on Stack Overflow
Try this :-
<input id="inputFile" type="file" onchange="convertToBase64();" />
<script type="text/javascript">
function convertToBase64() {
//Read File
var selectedFile = document.getElementById("inputFile").files;
//Check File is not Empty
if (selectedFile.length > 0) {
// Select the very first file from list
var fileToLoad = selectedFile[0];
// FileReader function for read the file.
var fileReader = new FileReader();
var base64;
// Onload of file read the file content
fileReader.onload = function(fileLoadedEvent) {
base64 = fileLoadedEvent.target.result;
// Print data in console
console.log(base64);
};
// Convert data to base64
fileReader.readAsDataURL(fileToLoad);
}
}
</script>
Here is how one person did it:
- http://blogs.adobe.com/formfeed/2009/08/base64_encode_a_pdf_attachment.html
Here is a link that suggests several other possible solutions:
- Base64 encoding and decoding in client-side Javascript
» npm install pdf-to-base64
How do I convert a PDF to Base64?
Is it safe to convert a PDF to Base64 online?
How much bigger is a PDF after Base64 encoding?
You can use HttpClient to get the file from url. First you have to import HttpClientModule in app.module.ts
import { HttpClientModule } from '@angular/common/http';
imports: [...,
'HttpClientModule',
...]
After that import in your component.ts HttpClient from '@angular/common/http' and add the instance in the constructor.
constructor(private http: HttpClient) { }
add the method
convertToBase64(url: string) {
this.http.get(url, { responseType: "blob" }).subscribe(blob => {
const reader = new FileReader();
const binaryString = reader.readAsDataURL(blob);
reader.onload = (event: any) => {
//Here you can do whatever you want with the base64 String
console.log("File in Base64: ", event.target.result);
};
reader.onerror = (event: any) => {
console.log("File could not be read: " + event.target.error.code);
};
});
}
function getBase64(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
reader.onerror = error => reject(error);
});
}
var file = document.querySelector('#files > input[type="file"]').files[0];
getBase64(file).then(
data => console.log(data)
);
Try this :-
<input id="inputFile" type="file" onchange="convertToBase64();" />
<script type="text/javascript">
function convertToBase64() {
//Read File
var selectedFile = document.getElementById("inputFile").files;
//Check File is not Empty
if (selectedFile.length > 0) {
// Select the very first file from list
var fileToLoad = selectedFile[0];
// FileReader function for read the file.
var fileReader = new FileReader();
var base64;
// Onload of file read the file content
fileReader.onload = function(fileLoadedEvent) {
base64 = fileLoadedEvent.target.result;
// Print data in console
console.log(base64);
};
// Convert data to base64
fileReader.readAsDataURL(fileToLoad);
}
}
</script>
From this
With Screw-FileReader & fetch
fetch('/file.pdf')
.then(res => res.blob())
.then(blob => blob.dataUrl())
.then(base64 => console.log(base64))
I could give you a few reason why you don't need the base64 string and why it's inconvenient. But i don't know why you need it... The overall reason is URL.createObjectURL and that it's ~3x larger
Worried that none of answer mentioned here has pointed this out, I am saying this:
File objects may be obtained from a FileList object returned as a result of a user selecting files using the element, or from a drag and drop operation's DataTransfer object. Source
Therefore only a code like below will work:
const fileInput = document.getElementById("fileInput");
const output = document.getElementById("output");
// Event listener when a user selects a file
fileInput.addEventListener("change", function(event) {
const file = event.target.files[0]; // Get the selected file
if (file && file.type === "application/pdf") {
const reader = new FileReader();
// Read the file as a Data URL (Base64)
reader.readAsDataURL(file);
reader.onload = function() {
const base64String = reader.result; // Base64 string
output.textContent = base64String.split(",")[1]; // Display Base64 data (without prefix)
console.log("Base64 PDF String:", base64String);
alert(base64String); // as stackoverflow console doesn't display
alert("See your browser console as well(not the SO console that will come below empty due to overflow/styling)")
};
reader.onerror = function(error) {
console.error("Error reading file:", error);
};
} else {
alert("Please select a valid PDF file.");
}
});
<h1>Select a PDF File to Read</h1>
<input type="file" id="fileInput" accept="application/pdf" />
<pre id="output"></pre>
Leo's answer will result in Uncaught TypeError: Failed to construct 'File': The provided value cannot be converted to a sequence. as xRdev said
xRdev's answer
var file = new File(["foo"], "/pdf/test.pdf", {type: 'application/pdf'});
creates a new empty file with just content "foo" inside it, simulating that it is stored in path "/pdf/test.pdf" so eventhough you get base64 it doesnt look like
data:application/pdf;base64,JVBERi0xLjUKJdDUxdgKNSAws2... but instead as data:application/pdf;base64,zsfasf
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);
};
}
from the sourcecode at http://mozilla.github.com/pdf.js/build/pdf.js
/**
* This is the main entry point for loading a PDF and interacting with it.
* NOTE: If a URL is used to fetch the PDF data a standard XMLHttpRequest(XHR)
* is used, which means it must follow the same origin rules that any XHR does
* e.g. No cross domain requests without CORS.
*
* @param {string|TypedAray|object} source Can be an url to where a PDF is
* located, a typed array (Uint8Array) already populated with data or
* and parameter object with the following possible fields:
* - url - The URL of the PDF.
* - data - A typed array with PDF data.
* - httpHeaders - Basic authentication headers.
* - password - For decrypting password-protected PDFs.
*
* @return {Promise} A promise that is resolved with {PDFDocumentProxy} object.
*/
So a standard XMLHttpRequest(XHR) is used for retrieving the document. The Problem with this is that XMLHttpRequests do not support data: uris (eg. data:application/pdf;base64,JVBERi0xLjUK...).
But there is the possibility of passing a typed Javascript Array to the function. The only thing you need to do is to convert the base64 string to a Uint8Array. You can use this function found at https://gist.github.com/1032746
var BASE64_MARKER = ';base64,';
function convertDataURIToBinary(dataURI) {
var base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length;
var base64 = dataURI.substring(base64Index);
var raw = window.atob(base64);
var rawLength = raw.length;
var array = new Uint8Array(new ArrayBuffer(rawLength));
for(var i = 0; i < rawLength; i++) {
array[i] = raw.charCodeAt(i);
}
return array;
}
tl;dr
var pdfAsDataUri = "data:application/pdf;base64,JVBERi0xLjUK..."; // shortened
var pdfAsArray = convertDataURIToBinary(pdfAsDataUri);
PDFJS.getDocument(pdfAsArray)
According to the examples base64 encoding is directly supported, although I've not tested it myself. Take your base64 string (derived from a file or loaded with any other method, POST/GET, websockets etc), turn it to a binary with atob, and then parse this to getDocument on the PDFJS API likePDFJS.getDocument({data: base64PdfData}); Codetoffel answer does work just fine for me though.