Friday, July 29, 2022

[FIXED] How to use a file read via "FileHandler" of "FileAccess API" inside "img" tag

Issue

Here's a detailed explanation on what I'm trying to do-

I'm reading a HTML file from a directory which has the image tag used but the assets are mapped locally and are not from url.

So somehow I'm able to get access to the file.

const fileHandle = await dirHandler.getFileHandle(file);

Now, I somehow want to use the content of this file inside img tag.

The way it's possible is using having a base64 url encoded file.

I'm not finding much stuff/detail on this.

A help would be highly appreciated.

Thanks


Solution

You don't need a base64 data url nor do you want it, instead create a blob: URL from the File object your FileHandle points to. To retrieve this File object, call the getFile() method of your handle.

const file = await fileHandle.getFile();
const url = URL.createObjectURL(file);
img.src = url;

or in a single line

img.src = URL.createObjectURL(await fileHandle.getFile());


Answered By - Kaiido
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.