Convert only filetype PDF to Base64

by Chance Nursey-Bush

HTML

<input type="file" accept="application/pdf" id="fileElement" onchange="convertToBase64(this)" />

<a id="downloadBtn" title='Download pdf document' download>Download File</a>

JavaScript

function x(fileElement) {
  //var fileElement = document.getElementById(elementId);
  var arr = [];

  if (fileElement) {
    //Read File
    var selectedFile = fileElement.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
        document.getElementById('downloadBtn').setAttribute('href',base64);
      };
      // Convert data to base64
      fileReader.readAsDataURL(fileToLoad);
    }
  }
}


window.convertToBase64 = x;