mirror of
https://github.com/tauri-apps/tauri.git
synced 2024-12-01 03:02:28 +03:00
feat(api): add convertFileSrc
helper (#2138)
This commit is contained in:
parent
06abe65569
commit
51a5cfe4b5
5
.changes/api-convert-file-url.md
Normal file
5
.changes/api-convert-file-url.md
Normal file
@ -0,0 +1,5 @@
|
||||
---
|
||||
"api": patch
|
||||
---
|
||||
|
||||
Adds `convertFileSrc` helper to the `tauri` module, simplifying the process of using file paths as webview source (`img`, `video`, etc).
|
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@ -79,10 +79,10 @@
|
||||
}
|
||||
],
|
||||
"security": {
|
||||
"csp": "default-src blob: data: filesystem: ws: wss: http: https: tauri: 'unsafe-eval' 'unsafe-inline' 'self' img-src: 'self'"
|
||||
"csp": "default-src blob: data: filesystem: ws: wss: http: https: tauri: asset: 'unsafe-eval' 'unsafe-inline' 'self' img-src: 'self'"
|
||||
},
|
||||
"systemTray": {
|
||||
"iconPath": "../../.icons/icon.png"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,9 +1,11 @@
|
||||
<script>
|
||||
import { readBinaryFile, readDir, Dir } from "@tauri-apps/api/fs";
|
||||
import { convertFileSrc } from "@tauri-apps/api/tauri";
|
||||
|
||||
export let onMessage;
|
||||
|
||||
let pathToRead = "";
|
||||
let img;
|
||||
|
||||
function getDir() {
|
||||
const dirSelect = document.getElementById("dir");
|
||||
@ -71,6 +73,10 @@
|
||||
})
|
||||
.catch(onMessage);
|
||||
}
|
||||
|
||||
function setSrc() {
|
||||
img.src = convertFileSrc(pathToRead)
|
||||
}
|
||||
</script>
|
||||
|
||||
<form on:submit|preventDefault={read}>
|
||||
@ -86,4 +92,7 @@
|
||||
bind:value={pathToRead}
|
||||
/>
|
||||
<button class="button" id="read">Read</button>
|
||||
<button class="button" type="button" on:click={setSrc}>Use as img src</button>
|
||||
|
||||
<img alt="file" bind:this={img}>
|
||||
</form>
|
||||
|
@ -88,6 +88,20 @@ async function invoke<T>(cmd: string, args: InvokeArgs = {}): Promise<T> {
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a device file path to an URL that can be loaded by the webview.
|
||||
* Note that `asset:` must be allowed on the `csp` value configured on `tauri.conf.json`.
|
||||
*
|
||||
* @param filePath the file path. On Windows, the drive name must be omitted, i.e. using `/Users/user/file.png` instead of `C:/Users/user/file.png`.
|
||||
*
|
||||
* @return the URL that can be used as source on the webview
|
||||
*/
|
||||
function convertFileSrc(filePath: string): string {
|
||||
return navigator.userAgent.includes('Windows')
|
||||
? `https://custom.protocol.asset_${filePath}`
|
||||
: `asset://${filePath}`
|
||||
}
|
||||
|
||||
export type { InvokeArgs }
|
||||
|
||||
export { transformCallback, invoke }
|
||||
export { transformCallback, invoke, convertFileSrc }
|
||||
|
Loading…
Reference in New Issue
Block a user