15

I am having some problems to take image as blob using jQuery:

Here is my code:

var file = $("#imgGaleria3")[0].files;

if (file) {
    var reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function(e) {
        // browser completed reading file - display it
        alert(e.target.result);
    };
}

And all the time im getting the same error: uncaught TypeError: Failed to execute 'readAsDataURL' on 'FileReader': parameter 1 is not of type 'Blob'.

How can I solve? I try some methods to read the data from file object with FileReader but nothing solves my problem.

Thx for ur help guys

5
  • you should put reader.readAsDataURL(file); after assigning the reader.onload. and $("#imgGaleria3")[0].files is an array of files . you should use $("#imgGaleria3")[0].files[0] Commented May 24, 2015 at 13:42
  • I dont understand why i should put : reader.readAsDataURL(file); after the reader.onload but u have the reason with the array of files.. thx too mate Commented May 24, 2015 at 17:00
  • Because it may finish reading the file even before attaching the on load function . Commented May 24, 2015 at 17:04
  • And how can i store this value? I need to store three images and some data more and have some problems because this func its async.. Commented May 24, 2015 at 18:56
  • You should put the same function at the end of each onload function, this function does tow things , first it makes sure all 3 are loaded or else it stoppes . if all 3 images are loaded it continues to execute. Commented May 25, 2015 at 4:33

2 Answers 2

24

This line looks wrong:

var file = $("#imgGaleria3")[0].files;

You need file to be a single file not all the files.

Example:

var file    = document.querySelector('input[type=file]').files[0];

or jQuery way:

var file = $("#imgGaleria3")[0].files[0];
Sign up to request clarification or add additional context in comments.

Comments

5

you're trying to execute the reader on an array.

try

var file = $("#imgGaleria3")[0].files[0];

if (file) {
    var reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function(e) {
        // browser completed reading file - display it
        alert(e.target.result);
    };
}

1 Comment

thanks, I test using Jquery fileinput plugin and it's works

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.