-1

I can get a file handle using the fairly-new File System Access API, and I'd like to set the file that it represents to the SRC property of an IMG element.

(This is a client-only application with JavaScript running the browser, but there is no web server, client-side or server-side. It's just an HTML file with embedded JavaScript.)

If I could get the complete path, I could just set that as the SRC. This works fine with a path that's a constant in the JavaScript. But, there is no way to get the absolute path with the File System Access API.

If I could somehow set the IMG element to access the file's contents via the file handle, that would work well, as I don't actually need the path for any other reason.

Any ideas?

(I've built local apps with Electron, where it's straightforward to get the path for a user-selected file, but I'm hoping I can do this with vanilla JavaScript.)

Marc Rochkind
  • 3,678
  • 3
  • 30
  • 38
  • Does this answer your question? [how to get the src for a video with File System Access API?](https://stackoverflow.com/questions/66012732/how-to-get-the-src-for-a-video-with-file-system-access-api) – esqew Jun 05 '22 at 23:25
  • That appears to provide a file name, which I have. It's the absolute path or some other way of setting the img src that I need. – Marc Rochkind Jun 07 '22 at 03:03

1 Answers1

2

You need to create a blob URL, which you can then assign to the src attribute of an img:

const [handle] = await showOpenFilePicker();
const file = await handle.getFile();
const img = document.createElement('img');
img.src = URL.createObjectURL(file);
document.body.append(img);
DenverCoder9
  • 2,024
  • 11
  • 32