0

I have image array. enter image description here

I want to move the selected image to the 1st place in the array by clicking enter image description here

enter image description here

$(document).on('click', '.newProductPic', function () {

$(".newProductPic").removeClass("selectImage");

$(this).addClass("selectImage");

var image = $(".selectImage")[0];
var fReader = new FileReader();

fReader.onloadend = (function (f) {
    return function (e) {

        var base64ImageString = this.result;
        var imageName = f.name;
        imagesListContent.push({ base64ImageString, imageName });

        addThumbMainImage(base64ImageString, f.name);
        currentMainImage = 'newProductPic' + i + '';
    };
})(image);

fReader.readAsDataURL(image);
var temp = $(".newProductPic")[0];

imagesListContent[0] = imagesListContent[selectMainImageId];

imagesListContent[selectMainImageId] = temp;
});

I'm getting a mistake: Uncaught TypeError: Failed to execute 'readAsDataURL' on 'FileReader': parameter 1 is not of type 'Blob'. What am I doing wrong and what are the solutions to this problem?

Andrew Stark
  • 105
  • 7
  • `image = $(".selectImage")[0]`, it's a jQuery object, taken from the DOM. The _file_reader expects a file to read, not a DOM element. – Jeremy Thille Sep 12 '19 at 12:24
  • If `.newProductPic` refers to an `input type="file"`, then you can just use [`this.files[0]`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file#files) to grab the file. – Heretic Monkey Sep 12 '19 at 12:31
  • @JeremyThille, ohh, I'm a fool. Can you tell us how we can solve this problem in another way? – Andrew Stark Sep 12 '19 at 12:33

1 Answers1

1

The argument you supply to the readAsDataURL should be a file reference than a jquery object.

<input type="file" id="files">


document.getElementById('files').addEventListener('change', handleFileSelect, fals)

The function will receive the event as an argument and you can get the file reference by event.currentTarget.files. This is an array

Another method is to get the file reference from the files array of the input element.

https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL

Charlie
  • 22,886
  • 11
  • 59
  • 90