2

I had been working on a component wherein when we upload an image from the desktop, It initially created an object URL using the URL.createObjectURL(). But, I recently read somewhere that createObjectURL is deprecated for the MediaStream. Also, I was getting this error:

"Failed to execute 'createObjectURL' on 'URL': Overload resolution failed."

I also got to know that we could set the srcObject to the MediaStream and that would work. But, for image upload, it was not working. Is there any way wherein I can create the temporary URL and set the img tag's src to that so that I am able to preview it on the web page? Any help is appreciated, Thanks!

Here is the code that I was previously using

const el = profilePicture.current;
const myMemoObj = URL.createObjectURL(event.target.files[0]);
el.src = URL.createObjectURL(event.target.files[0]);
URL.revokeObjectURL(myMemoObj);

I also tried setting the el.srcObject to event.target.files[0] but it didn't work out.

Edit: profilePicture is a ref attached to an img tag in the same component

profilePicture = useRef(null);
.
.
.
<img ref={profilePicture} alt="Profile Picture"/>
CSS-Romeo
  • 145
  • 7
  • 2
    unclear what .current is you don't need multiple createObjectURL's, if profilePicture is an img element then do profilePicture.src = myMemoObj then don't revoke it directly after. Most likely a dupe of https://stackoverflow.com/questions/4459379/preview-an-image-before-it-is-uploaded – Lawrence Cherone Apr 26 '22 at 14:22
  • 1
    @LawrenceCherone Sorry, I forgot to mention what profilePicture actually was. I have updated the post. It was a ref attached to the img tag. So, profilePicture.current is nothing but the img tag itself. Also, not revoking it immediately did work out. But I read somewhere that [createObjectURL is deprecated](https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL#usage_notes) and might not work in near future. Do we have any other workaround for previewing the image currently? – CSS-Romeo Apr 26 '22 at 16:28
  • 1
    that message is related to MediaStreams it's not a depreciation message and does not say it might not work in near future. It just mentions there is a [better way to attach the stream](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/srcObject#basic_example) which would require [fallback](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/srcObject#supporting_fallback_to_the_src_property) code anyway which uses createObjectURL, createObjectURL is not going away any time soon – Lawrence Cherone Apr 26 '22 at 19:18
  • 1
    @LawrenceCheroneThanks a lot for clarifying, I misunderstood that message related to MediaStreams. Thanks for the help! – CSS-Romeo Apr 27 '22 at 05:15

0 Answers0