如何将 fsPath 或任何绝对路径转换为 ​​VSCode API 中的 webview 资源 url?

How do I turn an fsPath or any absolute path into a webview resource url in VSCode API?

我需要的链接类似于:

https://file%2B.vscode-resource.vscode-webview.net/d%3A/Programming/Python/Lectures/Compilers/doobedoo/Episode2.mp4

我的路径如下所示: D:\Programming\Python\Lectures\Compilers\doobedoo\Episode2.mp4

问题是,我不能只是将字符串连接起来看起来像那个字符串,我需要一种方法让 VScode 为我完成它,以便它与操作系统、未来版本和使用时保持一致WSL.

对于上下文,我只能加载此内容策略下的资源:

<meta http-equiv="Content-Security-Policy" content="default-src 'none'; media-src %cspSource% https:; img-src %cspSource% https:; script-src 'nonce-%nonce%'; style-src %cspSource% 'unsafe-inline'; font-src %cspSource% ;" />

你看到了吗:webview docs

asWebviewUri(localResource: Uri): Uri

Convert a uri for the local file system to one that can be used inside webviews.

Webviews cannot directly load resources from the workspace or local file system using file: uris. The asWebviewUri function takes a local file: uri and converts it into a uri that can be used inside of a webview to load the same resource:

webview.html = `<img src="${webview.asWebviewUri(
  vscode.Uri.file('/Users/codey/workspace/cat.gif')
)}">`;

所以尝试:

yourWebview.asWebviewUri( vscode.Uri.file('D:\Programming\Python\Lectures\Compilers\doobedoo\Episode2.mp4'));