How to ensure that FileReader.onload() doesn't refresh the page

Viewed 868

I am trying to upload a form along with a file to google drive and while uploading the file, using FileReader, the file is getting uploaded but the page gets redirected to json success page like below.

{"result":"success","data":"\"https://drive.google.com/file/d/1dFXWqvAPu68""} 

var reader = new FileReader();
var file = document.getElementById('attach').files[0];
reader.onload = function() {
        document.getElementById('fileContent').value = reader.result;
        document.getElementById('filename').value = file.name;
        document.getElementById('gform').submit();
        }
reader.readAsDataURL(file);

I don't want the page to be redirected and when I tried using XMLHttpRequest to send form data along with the file, the file was uploading but it was invalid. How can I handle this?

1 Answers
reader.onload = function() {

  event.preventDefault()
  // your code here

}

https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault

The Event interface's preventDefault() method tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be. The event continues to propagate as usual, unless one of its event listeners calls stopPropagation() or stopImmediatePropagation(), either of which terminates propagation at once.

Related