Using Upload API

The upload API lets you upload files, such as images and videos, to be used within Builder.

A sample node js fetch code:

const fetch = require("node-fetch");
const fs = require('fs');

function upload_image(file) {
  // read binary data
  var bitmap = fs.readFileSync(file);
  fetch("https://builder.io/api/v1/upload", {
    method: "POST",
    body: bitmap,
    headers: {
     "Authorization": "Bearer builder-private-key",
     "Content-Type": "image/jpeg"
    },
 }).then(res => {
      return res.json();
 }).then(resp => {
     console.log(resp);
 }).catch((e) => console.log(e));
}
upload_image('./path-to-media');

Sample Javascript Fetch

var myHeaders = new Headers();
myHeaders.append("Authorization", "Bearer builder-private-key");
myHeaders.append("Content-Type", "image/jpeg");

var file = "<file contents here>"; // Binary data

var requestOptions = {
  method: 'POST',
  headers: myHeaders,
  body: file,
  redirect: 'follow'
};

fetch("https://builder.io/api/v1/upload", requestOptions)
  .then(response => response.text())
  .then(result => console.log(result))
  .catch(error => console.log('error', error));
1 Like

@manish-sharma Hey man,
I’m facing Authorization issue

{
“status”: 401,
“message”: “Authorization required”,
“detail”: “For help please contact support@builder.io”
}

Here is my code


  <TextField type="file" onChange={handleImageChange} />

  const handleImageChange = async (event: any) => {
    const file = event.target.files[0];
    try {
      const formData = new FormData();
      formData.append("file", file);
      const response = await uploadFileImageHandler(formData);
      console.log("Uploaded image URL:", response);
    } catch (error) {
      console.error("Error uploading image:", error);
    }
  };

import { fileUploadEndpoints } from "./constant";

export const uploadFileImageHandler = async (value: any) => {
  try {
    const response = await fetch(`${fileUploadEndpoints.fileUpload}`, {
      method: "POST",
      headers: {
        Authorization: `Bearer ${process.env.NEXT_PUBLIC_BUILDERIO_PUBLIC_API_KEY}`,
        "Content-Type": "image/png",
      },
      body: value,
    });
    const data = await response.json();
    return data;
  } catch (error) {
    return error;
  }
};

export const fileUploadEndpoints = Object.freeze({
  fileUpload: "https://builder.io/api/v1/upload",
});

Hello @hafiz,

I see you are using a public API key for the Bearer token which isn’t going to work, you will need to generate a private key and use that. You can refer to the below forum post for help on generating private key

Hi @manish-sharma,
i am trying to upload video using builder.io api
my code is

<TextField type="file" onChange={handleImageChange} />

 const handleImageChange = async (event: any) => {
    setIsLoading(true)
    const file = event.target.files[0]
    const fileName = file.name
    const fileExtension = fileName.split('.').pop()
    try {
      const response: any = await uploadFileVideoHandler(file, fileExtension)
      if (response && response?.url!) {
        setFeaturedVideoUrl(response?.url)
      }
      setIsLoading(false)
    } catch (err) {
      setIsLoading(false)
      showErrorSnackBar('Please try again to upload image')
    }
  }


export const uploadFileVideoHandler = async (
  value: any,
  fileExtension: string,
) => {
  try {
    const myHeaders = new Headers()
    myHeaders.append(
      'Authorization',
      `Bearer ${process.env.NEXT_PUBLIC_BUILDERIO_PRIVATE_API_KEY}`,
    )
    myHeaders.append('Content-Type', `video/${fileExtension}`)
    const requestOptions = {
      method: 'POST',
      headers: myHeaders,
      body: value,
    }
    const response = await fetch(
      `${fileUploadEndpoints.fileUpload}`,
      requestOptions,
    )
    const result = await response.json()
    return result
  } catch (error) {
    return error
  }
}

i am getting 500 error

Verifying that the server expects the file to be uploaded with the correct content type. In this case, the content type is set as video/${fileExtension} , which may not be suitable for all servers. Some servers may expect multipart/form-data or other specific content types for file uploads.

If possible, could you try to test the server-side file upload functionality using tools like Postman or cURL to isolate the issue further?