DEV Community

Discussion on: The anatomy of a custom input[type="file"] component

Collapse
 
pushp1992 profile image
Pushp Singh

Dude, no where you have mentioned where to write this code chunk,

function generatePreviewImgUrl(file, callback) {
const reader = new FileReader()
const url = reader.readAsDataURL(file)
reader.onloadend = e => callback(reader.result)
}

Even, you have nowhere initialised const url in your code.

After testing your code i am getting below data instead of image:

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAASwAAAEsCAYAAAB5fY51AAAABHNCSVQICAgIfAhkiAAAIABJREFUeJzsvXmYJEd1L/o7kUttXb33rJpNmkWjBbRcsRgJsQhJgC0BMsZgVj8D17425l4bf9d+z2Bh8PUzXvjs62ewsD/L1/Y1zyDggQVoQUhCIMBakIQYIYkRGs2MZnp6equ9KiPeH1lZHZ2dS2RWVnVVT/74millRpw4cfLEiXNOREYCKVKkSJEiRYoUKVKkSJEiRYoUKVIMNmi9GUgxXDh9+vSOTCazSQgxyRjLWpaVISJT0zSDiEzOualpmgkAlmU1GGMNIUTDsqymEKKhaVqdc14jotOLi4uz27Zte3a9+5RieJAarBQAQNVqdSfnfFLTtAnLss4RQuwjoj1EtJWIJoUQOgBdCGEyxkwhRIaINCGEBkADoBERY4xB13UAQKvVAuccQggOwAJgEZElhLCIqM45bxBRA

Your code seems to be buggy. please fix it and it will be great if you can attach codepen with your code.

Collapse
 
jsherz profile image
James Sherwood-Jones

If you're looking for how to structure your code, the Mozilla Developer Network has some great articles on starting web development and JavaScript: developer.mozilla.org/en-US/docs/L...

Collapse
 
greduan profile image
Eduardo Lavaque

Hey sorry for the slow response.

That function doesn't need a particular location. It just needs to be available to the code that needs it. So it's up to you where to put it.

As I recall, that output from the function is the correct output. It encodes the image into text and tells the img tag to load it from there when you put it in its src tag.

Collapse
 
pichuperez profile image
Gabriela Perez G

Agree with @Pushup Singh this is incomplete as it doesnt handle the correct image url to render the preview.