regist your protocol in main.js
:
protocol.registerSchemesAsPrivileged([
{
scheme: 'local-resource',
privileges: {
secure: true,
supportFetchAPI: true, // impotant
standard: true,
bypassCSP: true, // impotant
stream: true
}
}
])
then achieve protocol.handle func, pay attention to deal windows path drive letter.
app.whenReady().then(() => {
// 一个辅助函数,用于处理不同操作系统的文件路径问题
function convertPath(originalPath) {
const match = originalPath.match(/^\/([a-zA-Z])\/(.*)$/)
if (match) {
// 为 Windows 系统转换路径格式 恢复盘符
return `${match[1]}:/${match[2]}`
} else {
return originalPath // 其他系统直接使用原始路径
}
}
// 自定义协议对接为file协议
protocol.handle('local-resource', async (request) => {
const decodedUrl = decodeURIComponent(
request.url.replace(new RegExp(`^local-resource://`, 'i'), '/')
)
const fullPath = process.platform === 'win32' ? convertPath(decodedUrl) : decodedUrl
return net.fetch(`file://${fullPath}`)
})
createWindow()
})
use it. vue syntax
<template>
<img :src="`local-resource://E:/Download/tom.png`" />
</template>