Aftab Naveed
Aftab Naveed

Reputation: 3879

Electron JS Images from Local File System

I am new to electron and trying to load images from the local file system to display it on screen. So for images from the remote URLs are working just fine when I do

<img src='https://example.com/image.jpg' />

But when I try to load the same image from the local file system in my render process it does not work

<img src='file:///C:/tmp/image.jpg' />

is not rendered.

This is the error I got:

> Not allowed to load local resource:
> file:///C:/tmp/nW4jY0CHsepy08J9CkF1u3CJVfi4Yvzl_screenshot.png
> dashboard:1 Not allowed to load local resource:
> file:///C:/tmp/TOyUYWnJK7VS9wWeyABhdgCNmp38FyHt_screenshot.png

enter image description here

Is there any configuration that needs to be made to allow the electron to render images from the local file system Or I am doing it entirely wrong?

Upvotes: 31

Views: 36658

Answers (4)

Codeparl
Codeparl

Reputation: 335

I had similar problem building my electron+Vue app and here is what I did:

  1. I wrote a function to read images from disk
  2. I passed the function to electron api via window.api.myfunction
  3. In my renderer, I queried the element I wanted to display the image and passed the image as base64image

Below is the code:

1. read files from disk

  const readImageAsBase64 = (imagePath, callback) => {
      imagePath = getResourcePath('assets/' + imagePath)
    fs.readFile(imagePath, (error, data) => {
      const base64Image = data.toString('base64')
      if (data && typeof callback == 'function') callback(null, base64Image)
      else if (error && typeof callback == 'function') callback(error, null)
    })
  }

2. Passing my function to windows.api

 import myFiles from '../main/files'
 // Custom APIs for renderer
  const api = {
  studentDB,
  myFiles
 }

3. Using jquery and datatables, I displayed images for each item as follows

 $('#studentListTable tbody img[data-path]').each(function (i, o) {
        let $image = $(this),
        ext = $image.attr('data-path').afterLast('.'),
        path  = 'students/' + $image.attr('data-path')
         if (!$image.attr('data-path').startsWith('placeholder'))
          window.api.myFiles.readImageAsBase64(path, (error, data) => {
          $image.attr('src', 'data:image/' + ext + ';base64,' + data)
          })
         })

Upvotes: 0

Atana
Atana

Reputation: 91

I am working with an electron-react

"react": "^18.2.0", "electron": "^29.2.0"

app and I wanted to render images from my local drive. Because of security rules with electron, this is not an easy job. After the depreciation of electron protocol.registerFileProtocol(...), I spend hours trying to figure out how to work with protocol.handle(....).

// Deprecated in Electron 25
protocol.registerFileProtocol('some-protocol', () => {
  callback({ filePath: '/path/to/my/file' })
})

// Replace with
protocol.handle('some-protocol', () => {
  return net.fetch('file:///path/to/my/file')
})

electron docs

I managed to work it out like this:

main.js

app.whenReady().then(() => {
  protocol.handle('my-protocol', async (request, callback) => {
    const filePath = request.url.replace(`my-protocol://`, 'file://');
    return net.fetch(filePath);
  });

  createWindow();
});

MyReactComponent.jsx

...
<div>
  <img
     src={`my-protocol://${imageLocalPath}`}
     alt='my-alt'
     className='my-classname'
  />
</div>
...

Everything worked. I hope I helped!

Upvotes: 2

J. Reynolds
J. Reynolds

Reputation: 140

Method 1. Implement protocol.interceptFileProtocol with scheme 'file'.

Call callback with the file's directory path

Method 2. Implement session.defaultSession.webRequest.onBeforeRequest with a filter on 'file:///'.

In the callback load the file via node, convert to Base64 and return that.

Elaborating on Method 1:

protocol.interceptFileProtocol('resource', (req: ProtocolRequest, callback: (filePath: string) => void) => {

            if (someCondition) {

                const url = GetSomeFilePath(req.url);
                callback(url);

            }
            else {                

                callback(req.url);

            }            

        }); 

Upvotes: 4

Tarak
Tarak

Reputation: 517

Electron by default allows local resources to be accessed by render processes only when their html files are loaded from local sources with the file:// protocol for security reasons.

If you are loading the html from any http:// or https:// protocol even from a local server like webpack-dev-server, access to local resources is disabled.

If you loading html pages from a local server only during development and switching to local html files in production, you can disable websecurity during development, taking care to enable it in production.

If you are loading html from remote sources even in production, the best and secure way is to upload it somewhere on your server and load it.

Upvotes: 25

Related Questions