请稍等 ...
×

采纳答案成功!

向帮助你的同学说点啥吧!感谢那些助人为乐的人

protocol.handle 并没有拦截到 safe-file 导致图片无法显示

代码地址
图片描述
补充:
我做了如下的操作成功拦截到了

protocol.registerSchemesAsPrivileged([
  {
    scheme: 'safe-file',
    privileges: {
      standard: true,
      secure: true,
      supportFetchAPI: true,
    },
  },
])

app.whenReady().then(() => {
  protocol.handle('safe-file', async (request) => {
    console.log('request.url', request.url)
    const filePath = path.join(
      decodeURIComponent(request.url.slice('safe-file://'.length))
    )
    const newFilePath = pathToFileURL(filePath).toString()
    console.log('newFilePath', newFilePath)
    return net.fetch(newFilePath)
  })
})

图片描述
这是 windows环境下,我先把 filePath 做了一次 path.join ,这是为了解决 mac 和 windows / \ 的问题,但是使用 pathToFileURL 方法 会把 当前 路径(D:/electron-ai)自动拼接到 正确路径(c/Users/admin/AppData/Roaming/electron-ai/images/%E9%A5%AE%E9%A3%9F%E6%B3%A8%E6%84%8F.png)的前面 ,这个问题未解决

终于解决,但是不知道 mac 上是否能够运行,代码如下:

protocol.handle('safe-file', async (request) => {
    const userDataPath = app.getPath('userData')
    const imageDir = path.join(userDataPath, 'images')
    const filePath = path.join(
      decodeURIComponent(request.url.slice('safe-file:/'.length))
    )
    const filename = path.basename(filePath)
    const fileAddr = path.join(imageDir, filename)
    const newFilePath = pathToFileURL(fileAddr).toString()
    return net.fetch(newFilePath)
  })

感觉写的很垃圾,不知道有没有什么更好的写法

正在回答 回答被采纳积分+3

插入代码

2回答

张轩 2025-03-23 15:32:46

同学你好

非常感谢你的回答,我昨天也搜到了类似的解决方案,看来 windows 电脑是必须要用 protocol.registerSchemesAsPrivileged

这个方法的

还有就是对于windows的 path 需要特殊处理, 可以使用 URL 这个内置模块试一试,它是标准方法,更好用,请看 https://gist.github.com/vikingmute/6d40dabf54eeaaccacba655a8d96e09d

不知道为什么代码在慕课网保存失败,应该是什么安全措施。

你可以帮我测试一下是否在 windows 下面可用


0 回复 有任何疑惑可以回复我~
张轩 2025-03-22 21:19:57

同学你好

请问你这里拦截协议对应的回掉有任何的返回吗?因为我的机器不是windows 的,所以希望你再提供一些信息。

0 回复 有任何疑惑可以回复我~
  • 提问者 Q7715529 #1
    没有,连这个拦截都没有进去,里面没有任何log
    回复 有任何疑惑可以回复我~ 2025-03-22 22:08:35
  • 提问者 Q7715529 #2
    重现编辑了问题,可以查看一下
    回复 有任何疑惑可以回复我~ 2025-03-22 23:00:38
  • 不用那么复杂,有个简便方法可以解决
    回复 有任何疑惑可以回复我~ 2025-04-01 19:14:35

相似问题

登录后可查看更多问答,登录/注册

问题已解决,确定采纳
还有疑问,暂不采纳
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号