代码地址
补充:
我做了如下的操作成功拦截到了
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)
})
感觉写的很垃圾,不知道有没有什么更好的写法
文心一言/通义千问/Deepseek/ Claude/Cursor与Vue3、Electron
了解课程