Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 1 addition & 5 deletions astro.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,6 @@ import react from "@astrojs/react";

// https://astro.build/config
export default defineConfig({
base: "/app",
build: {
assetsPrefix: "/app",
},
security: {
checkOrigin: false,
},
Expand All @@ -33,4 +29,4 @@ export default defineConfig({
: undefined,
},
},
});
});
3 changes: 3 additions & 0 deletions public/favicon.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
29 changes: 16 additions & 13 deletions src/components/FileUploader.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,13 @@ interface FileData {
};
}

export default function FileUploader() {
interface FileUploaderProps {
mountPath?: string;
}

export default function FileUploader({ mountPath = "/" }: FileUploaderProps) {
const apiBase =
typeof window !== "undefined" ? window.location.origin + mountPath : mountPath;
const [isUploading, setIsUploading] = useState(false);
const [progress, setProgress] = useState(0);
const [files, setFiles] = useState<FileData[]>([]);
Expand Down Expand Up @@ -70,7 +76,7 @@ export default function FileUploader() {
const loadFiles = async () => {
try {
setLoading(true);
const response = await fetch(`${import.meta.env.BASE_URL}/api/list-assets`);
const response = await fetch(new URL('api/list-assets', apiBase));

if (!response.ok) {
throw new Error("Failed to load files");
Expand Down Expand Up @@ -119,7 +125,7 @@ export default function FileUploader() {
formData.append("file", file);


const response = await fetch(`${import.meta.env.BASE_URL}/api/upload`, {
const response = await fetch(new URL('api/upload', apiBase), {
method: "POST",
body: formData,
});
Expand Down Expand Up @@ -154,14 +160,13 @@ export default function FileUploader() {
setProgress(0);

try {
const assetsPrefix = import.meta.env.ASSETS_PREFIX || "";
const BASE_CF_URL = `${assetsPrefix}/api/multipart-upload`;
const BASE_CF_URL = new URL('api/multipart-upload', apiBase);
const key = file.name;
const CHUNK_SIZE = 5 * 1024 * 1024; // 5MB
const totalParts = Math.ceil(file.size / CHUNK_SIZE);

// Step 1: Initiate upload
const createUploadUrl = new URL(BASE_CF_URL, window.location.origin);
const createUploadUrl = new URL(BASE_CF_URL);
createUploadUrl.searchParams.append("action", "create");

const createResponse = await fetch(createUploadUrl, {
Expand All @@ -175,7 +180,7 @@ export default function FileUploader() {

// Step 2: Upload parts
const partsData = [];
const uploadPartUrl = new URL(BASE_CF_URL, window.location.origin);
const uploadPartUrl = new URL(BASE_CF_URL);
uploadPartUrl.searchParams.append("action", "upload-part");
uploadPartUrl.searchParams.append("uploadId", uploadId);
uploadPartUrl.searchParams.append("key", key);
Expand Down Expand Up @@ -206,7 +211,7 @@ export default function FileUploader() {
}

// Step 3: Complete upload
const completeUploadUrl = new URL(BASE_CF_URL, window.location.origin);
const completeUploadUrl = new URL(BASE_CF_URL);
completeUploadUrl.searchParams.append("action", "complete");

const completeResponse = await fetch(completeUploadUrl, {
Expand Down Expand Up @@ -524,11 +529,9 @@ export default function FileUploader() {
{files.map((file, index) => {
const fileName = file.name || file.key || "Unknown file";
const fileKey = file.key || file.name || `file-${index}`;
const fileLink =
file.link ||
(file.key
? `${import.meta.env.ASSETS_PREFIX}/api/asset?key=${file.key}`
: "");
const assetUrl = new URL('api/asset', apiBase);
if (file.key) assetUrl.searchParams.set('key', file.key);
const fileLink = file.link || (file.key ? assetUrl.href : "");
const uploadDate =
file.dateUploaded || file.uploaded || new Date().toISOString();
const isImageFile = isImage(fileName);
Expand Down
4 changes: 3 additions & 1 deletion src/layouts/Layout.astro
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
---
import "../assets/globals.css";
import { getMountPath } from "../utils/mountPath";

const base = getMountPath(Astro.locals);
---

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width" />
<link rel="icon" type="image/svg+xml" href={`${import.meta.env.BASE_URL}/favicon.svg`} />
<link rel="icon" type="image/svg+xml" href={`${base}favicon.svg`} />
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@100..900&display=swap" rel="stylesheet">
Expand Down
82 changes: 42 additions & 40 deletions src/pages/files.astro
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
---
import Layout from '../layouts/Layout.astro';
import { getMountPath } from '../utils/mountPath';

// Get the assets prefix from environment
const assetsPrefix = Astro.locals.runtime?.env?.ASSETS_PREFIX || '/app';
const mountPath = getMountPath(Astro.locals);
---

<Layout title="File Uploader">
<div class="container mx-auto p-6 max-w-6xl">
<div class="container mx-auto p-6 max-w-6xl" data-mount-path={mountPath}>
<h1 class="text-4xl font-bold text-center mb-8">File Uploader</h1>

<!-- Upload Section -->
<div class="card bg-base-100 shadow-xl mb-8">
<div class="card-body">
Expand All @@ -18,23 +18,23 @@ const assetsPrefix = Astro.locals.runtime?.env?.ASSETS_PREFIX || '/app';
<label class="label">
<span class="label-text">Select Files</span>
</label>
<input
type="file"
id="fileInput"
multiple
class="file-input file-input-bordered w-full"
<input
type="file"
id="fileInput"
multiple
class="file-input file-input-bordered w-full"
accept="image/*,video/*,audio/*,.pdf,.doc,.docx,.txt,.zip,.rar"
/>
</div>

<div class="form-control">
<button type="submit" class="btn btn-primary" id="uploadBtn">
<span class="loading loading-spinner loading-sm hidden" id="uploadSpinner"></span>
Upload Files
</button>
</div>
</form>

<!-- Upload Progress -->
<div id="uploadProgress" class="hidden mt-4">
<div class="progress progress-primary w-full">
Expand All @@ -55,16 +55,16 @@ const assetsPrefix = Astro.locals.runtime?.env?.ASSETS_PREFIX || '/app';
Refresh
</button>
</div>

<div id="filesList" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
<!-- Files will be loaded here -->
</div>

<div id="loadingFiles" class="text-center py-8">
<span class="loading loading-spinner loading-lg"></span>
<p class="mt-2">Loading files...</p>
</div>

<div id="noFiles" class="text-center py-8 hidden">
<div class="text-6xl mb-4">📁</div>
<p class="text-lg">No files uploaded yet</p>
Expand All @@ -76,8 +76,10 @@ const assetsPrefix = Astro.locals.runtime?.env?.ASSETS_PREFIX || '/app';
</Layout>

<script>
const assetsPrefix = '${assetsPrefix}';

const mountPath =
document.querySelector<HTMLElement>('[data-mount-path]')?.dataset.mountPath || '/';
const baseUrl = window.location.origin + mountPath;

// DOM elements
const uploadForm = document.getElementById('uploadForm') as HTMLFormElement;
const fileInput = document.getElementById('fileInput') as HTMLInputElement;
Expand Down Expand Up @@ -111,15 +113,15 @@ const assetsPrefix = Astro.locals.runtime?.env?.ASSETS_PREFIX || '/app';
if (ext && fileIcons[ext]) {
return fileIcons[ext];
}

// Check if it's a video or audio file
if (filename.match(/\.(mp4|avi|mov|wmv|flv|webm|mkv)$/i)) {
return fileIcons.video;
}
if (filename.match(/\.(mp3|wav|flac|aac|ogg|wma)$/i)) {
return fileIcons.audio;
}

return fileIcons.default;
}

Expand Down Expand Up @@ -160,32 +162,32 @@ const assetsPrefix = Astro.locals.runtime?.env?.ASSETS_PREFIX || '/app';
try {
loadingFiles.classList.remove('hidden');
filesList.innerHTML = '';
const response = await fetch(`${assetsPrefix}/api/list-assets`);

const response = await fetch(new URL('api/list-assets', baseUrl));
if (!response.ok) {
throw new Error('Failed to load files');
}

const files = await response.json() as FileItem[];

loadingFiles.classList.add('hidden');

if (files.length === 0) {
noFiles.classList.remove('hidden');
return;
}

noFiles.classList.add('hidden');

files.forEach((file: FileItem) => {
const fileCard = document.createElement('div');
fileCard.className = 'card bg-base-200 shadow-sm hover:shadow-md transition-shadow';

const isImageFile = isImage(file.name);

fileCard.innerHTML = `
<figure class="px-4 pt-4">
${isImageFile
${isImageFile
? `<img src="${file.link}" alt="${file.name}" class="rounded-xl h-32 w-full object-cover" />`
: `<div class="flex items-center justify-center h-32 w-full bg-base-300 rounded-xl">
<span class="text-4xl">${getFileIcon(file.name)}</span>
Expand All @@ -202,7 +204,7 @@ const assetsPrefix = Astro.locals.runtime?.env?.ASSETS_PREFIX || '/app';
</div>
</div>
`;

filesList.appendChild(fileCard);
});
} catch (error) {
Expand All @@ -221,52 +223,52 @@ const assetsPrefix = Astro.locals.runtime?.env?.ASSETS_PREFIX || '/app';
// Handle file upload
async function handleUpload(event: Event) {
event.preventDefault();

const files = fileInput.files;
if (!files || files.length === 0) {
alert('Please select files to upload');
return;
}

// Show loading state
uploadBtn.disabled = true;
uploadSpinner.classList.remove('hidden');
uploadProgress.classList.remove('hidden');

try {
for (let i = 0; i < files.length; i++) {
const file = files[i];
const formData = new FormData();
formData.append('file', file);

// Update progress
const progress = ((i + 1) / files.length) * 100;
progressBar.style.width = `${progress}%`;
progressText.textContent = `Uploading ${file.name}...`;
const response = await fetch(`${assetsPrefix}/api/upload`, {

const response = await fetch(new URL('api/upload', baseUrl), {
method: 'POST',
body: formData
});

if (!response.ok) {
throw new Error(`Failed to upload ${file.name}`);
}
}

// Success
progressText.textContent = 'Upload completed!';
progressBar.style.width = '100%';

// Reset form
fileInput.value = '';

// Reload files list
setTimeout(() => {
loadFiles();
uploadProgress.classList.add('hidden');
}, 1000);

} catch (error) {
console.error('Upload error:', error);
progressText.textContent = 'Upload failed!';
Expand Down
5 changes: 4 additions & 1 deletion src/pages/index.astro
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
---
import Layout from '../layouts/Layout.astro';
import FileUploader from '../components/FileUploader';
import { getMountPath } from '../utils/mountPath';

const mountPath = getMountPath(Astro.locals);
---

<Layout>
<main>
<FileUploader client:load />
<FileUploader client:load mountPath={mountPath} />
</main>
</Layout>

Expand Down
10 changes: 10 additions & 0 deletions src/utils/mountPath.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
// Returns the deployment's mount path as a base URL guaranteed to start
// and end with "/". Cosmic injects COSMIC_MOUNT_PATH as a worker env var
// (e.g. "/" for root deployments, "/app" for sub-path deployments).
export function getMountPath(locals: App.Locals): string {
const raw =
(locals?.runtime?.env as Record<string, string> | undefined)
?.COSMIC_MOUNT_PATH ?? "/";
const trimmed = raw.replace(/^\/|\/$/g, "");
return trimmed ? `/${trimmed}/` : "/";
}