Cloudflare Images -- direct creator uploads using tus-client

Hello,
I’m creating a Next.js app where the users will upload Videos and Images.
Video uploading works great, but I cannot use tus-client to upload images. I get the upload URL, upload doesn’t start. This is my API for the one-time URL

export async function POST(req: NextRequest, { params }: { params: { brandId: string } }) {

    const endpoint = `https://api.cloudflare.com/client/v4/accounts/${cfAccountId}/images/v2/direct_upload`;
  const uploadLength = req.headers.get('Upload-Length') || '';
  const uploadMetadata = req.headers.get('Upload-Metadata') || '';

  const response = await fetch(endpoint, {
    method: 'POST',
    headers: {
      Authorization: `bearer ${cfApiToken}`,
      'Tus-Resumable': '1.0.0',
      'Upload-Length': uploadLength,
      'Upload-Metadata': uploadMetadata,
      'Upload-Creator': brand.id,
    },
  });

  if (!response.ok) {
    logger.error(`Failed to create stream: ${response.statusText}`);
    return NextResponse.json({ error: 'Failed to create stream.' }, { status: response.status });
  }

  const data: CfImageGetUploadUrlResponse = await response.json();
  const destination = data.result.uploadURL;

  if (destination) {
    logger.log(`Stream created successfully. Destination: ${destination}`);

    const response = NextResponse.json({}, { status: 200 });
    response.headers.set('Location', destination);
    response.headers.set('Access-Control-Expose-Headers', 'Location');
    response.headers.set('Access-Control-Allow-Headers', '*');
    response.headers.set('Access-Control-Allow-Origin', '*');
    return response;
  } else {
    logger.error('Failed to obtain upload URL from Cloudflare.');
    return NextResponse.json({ error: 'Failed to obtain upload URL' }, { status: 500 });
  }
}

And this is my client-side

        const upload = new tusUpload(file, {
          endpoint: `/api/assets/${brandId}/image/uploadDirectCreator`,
          chunkSize: 2 * 1024 * 1024,
          retryDelays: [0, 1000, 3000, 5000],
          metadata: {
            filename: file.name,
            filetype: file.type,
            name: file.name,
            hash,
          },
          uploadSize: file.size,
          onError: (error) => {
            console.error('Upload failed:', error);
            setUploadStatus(uploadStatus);
            reject(error);
          },

Sorry, not familiar with tus client, what error do you get?

Using the above code I get the one-time URL, but the upload doesn’t start. I suppose the tus-client config is not correct or not supported.
I’m using the tus-client for video uploads using a code adjusted from this example: Direct creator uploads · Cloudflare Stream docs

I was trying to get a similar setup for image upload. If not, is it possible to see the progress of the image upload? I haven’t found any examples.

I suppose the tus-client config is not correct or not supported.

I see now, TUS protocol is not supported for images. It’s a simple plain HTTP that accepts multipart/form-data body.

is it possible to see the progress of the image upload? I haven’t found any examples.

Once you receive a response from direct upload api Cloudflare API Documentation

you can use an image id to verify it’s status. From the docs above:

This method creates a draft record for a future image. It returns an upload URL and an image identifier. To verify if the image itself has been uploaded, send an image details request (accounts/:account_identifier/images/v1/:identifier), and check that the draft: true property is not present.

Ah ok! If the draft: true property is present, is the upload % or any other property available that can help me track the upload progress?

Images don’t have progress on uploads. It’s either uploaded or not, hence the boolean flag.

This topic was automatically closed after 15 days. New replies are no longer allowed.