Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get blob image from file input using jQuery

Tags:

html

jquery

file

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

like image 611
Nega developer Avatar asked May 24 '15 13:05

Nega developer


2 Answers

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];
like image 189
T McKeown Avatar answered Nov 17 '22 22:11

T McKeown


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);
    };
}
like image 40
John M Avatar answered Nov 17 '22 22:11

John M