Campbell
Campbell

Reputation: 406

Electron: how to serve files from appdata

I feel like this is such a basic question but I have been at it for hours and seem to be spinning around the answer. I have an electron app which I also used create-react-app on. I have image files in the appData folder for the electron app and I want to be able to display them in the renderer (using react) using an img tag.

I cannot seem to figure out how to do this. Using an absolute path and file:// for the img src doesn't work. I also tried to register a custom protocol but can't seem to get it to work, I just keep getting file not found (see below). Any ideas or links would be appreciated.

  protocol.registerFileProtocol('poster', (request, callback) => {
    const url = request.url.substr(9)
    console.log(url);
    callback({path: app.getPath('appData')+'/posters/'+url})
  }, (error) => {
    if (error) console.error('Failed to register protocol')
  })

The image tag would look something like this:

<img src='poster://test.jpg'/>

Upvotes: 3

Views: 3310

Answers (1)

Campbell
Campbell

Reputation: 406

What I eventually ended up doing was correcting my original code to use userData instead of appData. I didn't end up solving the part where it was converting to lower case so I just made all of my file names in lower case.

To find the path on your machine where you should put the files you can look at the result of a call to:

app.getPath('userData')

Here is the relevant code in my public/electron.js file:

  protocol.registerFileProtocol('poster', (request, callback) => {
          const url = request.url.substr(9,request.url.length -10)
          callback({path: app.getPath('userData')+'/posters/'+url})
        }, (error) => {
          if (error) console.error('Failed to register protocol')
        })

  }

  protocol.registerStandardSchemes(['poster'])

In my react code it is just a matter now of prefixing the filename in my image tag with 'poster://' so an image tag looks like:

<img src='poster://poster1.jpg/>

Upvotes: 2

Related Questions