Skip to content
Back

Upload large files with progress feedback.

  • 0
  • Storage
  • REST API
xmaniaxz
26 Feb, 2025, 12:45

Hi, I am working on my own CMS and i want to have storage containers for files. However some of them will be quite large. (3GB)

I am using NextJS and Appwrite together but i keep running into either 1 of 2 issues.

  1. When running the upload client side, the upload stops the moment someone refreshes the page.
  2. When running the upload server side, i can't send back the progress. (using NextJS route handler for api also doesnt work as it cant parse the body as formdata with Files. )
TL;DR
Developers wanted to upload large files with progress feedback using NextJS and Appwrite. They faced issues with client-side upload stopping on page refresh and server-side upload not sending back progress. To resolve the server-side issue, they can update the `POST` function in `/app/api/upload/route.ts` to return progress in the response.
xmaniaxz
26 Feb, 2025, 12:45

/app/api/upload/route.ts

TypeScript
import { NextResponse } from "next/server";
import { Client, ID, Storage } from "node-appwrite";
// In-memory object to store progress for each file
let progressData: { [key: string]: { progress: number; fileName: string } } =
  {};

export async function GET(req: Request) {
  const url = new URL(req.url);
  const fileId = url.searchParams.get("fileId");

  if (!fileId || !progressData[fileId]) {
    return NextResponse.json({ error: "File ID not found" }, { status: 404 });
  }

  return NextResponse.json({ progress: progressData[fileId].progress, fileName: progressData[fileId].fileName });
}

export async function POST(req: Request) {
  const formData:FormData = await req.formData();
  const file:File = formData.get("file") as File;
  const bucketID : string= "67aa1870001eaadbdcbb";
  const fileExists : boolean = await FileNameExists(bucketID, file.name);
  if (!file) {
    return NextResponse.json({ error: "No file uploaded" }, { status: 400 });
  }

  const fileId = crypto.randomUUID();
  progressData[fileId] = { progress: 0, fileName: file.name };

  const storage = new Storage(await CreateAdminClient());

  let response;

  console.log("Starting upload");

  response = await storage.createFile(
    bucketID,
    fileExists ? fileId : ID.unique(),
    file,
    [],
    (progress) => {
      progressData[fileId].progress = progress.progress;
    }
  );

  return NextResponse.json({ fileId, progress: progressData[fileId].progress });
}
Reply

Reply to this thread by joining our Discord

Reply on Discord

Need support?

Join our Discord

Get community support by joining our Discord server.

Join Discord

Get premium support

Join Appwrite Pro and get email support from our team.

Learn more