fix: add authentication to file downloads #42

Merged
jimmy merged 1 commits from dev into main 2026-04-09 23:17:08 +08:00
2 changed files with 26 additions and 4 deletions
Showing only changes of commit 1ff48ab86d - Show all commits
+22
View File
@@ -197,3 +197,25 @@ export function getInfoEngineItem(id) {
export function put(path, data) { export function put(path, data) {
return request(path, { method: "PUT", json: data }); return request(path, { method: "PUT", json: data });
} }
export async function download(path, filename) {
const headers = {};
if (token) headers["Authorization"] = `Bearer ${token}`;
const r = await fetch(`${BASE}/files/download?path=${encodeURIComponent(path)}`, {
method: "GET",
headers,
});
if (!r.ok) throw new Error(`HTTP ${r.status}`);
const blob = await r.blob();
const url = window.URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
document.body.removeChild(a);
}
+4 -4
View File
@@ -1,6 +1,6 @@
<script> <script>
import { onMount } from "svelte"; import { onMount } from "svelte";
import { get, del, upload } from "../lib/api.js"; import { get, del, upload, download } from "../lib/api.js";
let entries = $state([]); let entries = $state([]);
let currentPath = $state(""); let currentPath = $state("");
@@ -29,9 +29,9 @@
browse(currentPath); browse(currentPath);
} }
function downloadUrl(name) { async function handleDownload(name) {
const path = currentPath ? `${currentPath}/${name}` : name; const path = currentPath ? `${currentPath}/${name}` : name;
return `/api/files/download?path=${encodeURIComponent(path)}`; await download(path, name);
} }
async function handleUpload() { async function handleUpload() {
@@ -137,7 +137,7 @@
<span class="text-xs text-surface-400 text-right">{e.is_dir ? "—" : formatSize(e.size)}</span> <span class="text-xs text-surface-400 text-right">{e.is_dir ? "—" : formatSize(e.size)}</span>
<div class="flex items-center justify-end gap-1 opacity-0 group-hover:opacity-100 transition-opacity"> <div class="flex items-center justify-end gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
{#if !e.is_dir} {#if !e.is_dir}
<a href={downloadUrl(e.name)} class="text-[11px] text-primary-500 hover:text-primary-700 font-medium transition-colors">DL</a> <button onclick={() => handleDownload(e.name)} class="text-[11px] text-primary-500 hover:text-primary-700 font-medium transition-colors">DL</button>
{/if} {/if}
<button class="text-[11px] text-rose-400 hover:text-rose-600 font-medium transition-colors" onclick={() => remove(e.name)}>Del</button> <button class="text-[11px] text-rose-400 hover:text-rose-600 font-medium transition-colors" onclick={() => remove(e.name)}>Del</button>
</div> </div>