Niccolò Caselli
Niccolò Caselli

Reputation: 882

Unable to upload audio files to Cloudinary API (with javascript)

In my react native application I have implemented a function to upload an image to Cloudinary and this works perfectly. However now I need to upload audio files too, so I readjusted the function but, despite having specified the "resource_type" parameter to "raw" (I also tried with "video" and "auto") I get the error [Error : Invalid image file].

const CLOUDINARY_UPLOAD_URL = `https://api.cloudinary.com/v1_1/${CLOUD_NAME}/image/upload`;

// takes base64 audio file as argument
export const uploadAudio = async (
    audio: string
  ): Promise<UploadImageResult> => {
    

    // function that requests  a signature to my API in order to load the resource 
    const {
      signature,
      timestamp,
      upload_preset,
    } = await getCloudinarySignature();
  

    const formData = new FormData();
    formData.append("file", audio);
    formData.append("resource_type", "raw");
    formData.append("signature", signature);
    formData.append("timestamp", timestamp);
    formData.append("upload_preset", upload_preset);
    formData.append("api_key", API_KEY);
  

    const res = await fetch(CLOUDINARY_UPLOAD_URL, {
      method: "POST",
      body: formData,
    });
  
    const data = await res.json();
  
    if (!res.ok || !data.secure_url) throw new Error(data.error.message);
  
    return {
      url: data.secure_url,
      asset_id: data.asset_id,
      public_id: data.public_id,
    };
  };

Does anyone know what I'm doing wrong? Thank you.

Upvotes: 0

Views: 918

Answers (1)

Aleksandar
Aleksandar

Reputation: 1698

The resource_type is part of the Upload API endpoint (CLOUDINARY_UPLOAD_URL in your case) rather than as part of Form parameters, and since your URL is always using /image/upload that will be the resource_type that is checked against resulting in the error.

What you can do is remove the resource_type form parameter and based on the filetype set the appropriate path in the URL e.g. /video/upload (for videos and audio) or /raw/upload for other filetypes such as txt, json etc.

Alternatively, you can just set the value as /auto/upload and you can upload any filetype without needing to change it to 'image', 'video' or 'raw' specifically. 'auto' will leave the logic to Cloudinary to determine the right resource_type to use per-asset.

Upvotes: 1

Related Questions