mirror of
https://github.com/tauri-apps/plugins-workspace.git
synced 2026-06-06 13:53:54 +02:00
feat(upload): Add function to download files (#89)
This commit is contained in:
@@ -11,12 +11,12 @@ type ProgressHandler = (progress: number, total: number) => void;
|
||||
const handlers: Map<number, ProgressHandler> = new Map();
|
||||
let listening = false;
|
||||
|
||||
async function listenToUploadEventIfNeeded(): Promise<void> {
|
||||
async function listenToEventIfNeeded(event: string): Promise<void> {
|
||||
if (listening) {
|
||||
return await Promise.resolve();
|
||||
}
|
||||
return await appWindow
|
||||
.listen<ProgressPayload>("upload://progress", ({ payload }) => {
|
||||
.listen<ProgressPayload>(event, ({ payload }) => {
|
||||
const handler = handlers.get(payload.id);
|
||||
if (handler != null) {
|
||||
handler(payload.progress, payload.total);
|
||||
@@ -27,7 +27,7 @@ async function listenToUploadEventIfNeeded(): Promise<void> {
|
||||
});
|
||||
}
|
||||
|
||||
export default async function upload(
|
||||
async function upload(
|
||||
url: string,
|
||||
filePath: string,
|
||||
progressHandler?: ProgressHandler,
|
||||
@@ -41,7 +41,7 @@ export default async function upload(
|
||||
handlers.set(id, progressHandler);
|
||||
}
|
||||
|
||||
await listenToUploadEventIfNeeded();
|
||||
await listenToEventIfNeeded("upload://progress");
|
||||
|
||||
await invoke("plugin:upload|upload", {
|
||||
id,
|
||||
@@ -50,3 +50,30 @@ export default async function upload(
|
||||
headers: headers ?? {},
|
||||
});
|
||||
}
|
||||
|
||||
async function download(
|
||||
url: string,
|
||||
filePath: string,
|
||||
progressHandler?: ProgressHandler,
|
||||
headers?: Map<string, string>
|
||||
): Promise<void> {
|
||||
const ids = new Uint32Array(1);
|
||||
window.crypto.getRandomValues(ids);
|
||||
const id = ids[0];
|
||||
|
||||
if (progressHandler != null) {
|
||||
handlers.set(id, progressHandler);
|
||||
}
|
||||
|
||||
await listenToEventIfNeeded("download://progress");
|
||||
|
||||
await invoke("plugin:upload|upload", {
|
||||
id,
|
||||
url,
|
||||
filePath,
|
||||
headers: headers ?? {},
|
||||
});
|
||||
}
|
||||
|
||||
export default upload;
|
||||
export { download, upload };
|
||||
|
||||
Reference in New Issue
Block a user