3

I have an image file in the form of a JavaScript File object. I was to add it to an <img> tag so I can render it in my React project. This is going to be used in my Client side code so I do not want it to be downloaded. I was looking at a few similar (but not exact) questions and they all use a FileReader but I cannot seem to get it to work. I keep getting an ImagePreview.js:25 Uncaught TypeError: Failed to execute 'readAsDataURL' on 'FileReader': parameter 1 is not of type 'Blob'.. My object is a File object which is a type of Blob according to the Mozilla document. Maybe I am confused? Could someone point me in the right direction? This is what the object looks like when I print it to the console:

File {name: 'gopher1.png', lastModified: 1633647754682, lastModifiedDate: Thu Oct 07 2021 18:02:34 GMT-0500 (Central Daylight Time), webkitRelativePath: '', size: 34156, …}
lastModified: 1633647754682
lastModifiedDate: Thu Oct 07 2021 18:02:34 GMT-0500 (Central Daylight Time) {}
name: "gopher1.png"
size: 34156
type: ""
webkitRelativePath: ""
[[Prototype]]: File
3
  • 1
    Can you share a code sandbox with a demo of what you have so far in terms of code? Commented Oct 8, 2021 at 0:34
  • 2
    You are certainly not passing what you think to this method, but note that you should not use a FileReader here anyway. To render the image from the Blob, create a blob URL. Commented Oct 8, 2021 at 2:10
  • @Kaiido this is exactly what I am looking for! Had to do a few tweaks but it works, thank you! Commented Oct 8, 2021 at 5:42

1 Answer 1

6

I believe you do

const url = URL.createObjectURL(file)

then use url as a src

Sign up to request clarification or add additional context in comments.

Comments

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.