Having trouble transferring sound files to Cloudinary API through javascript

I have successfully implemented a function in my React Native application to upload images to Cloudinary. Now, I am trying to modify the function to upload audio files as well. Despite specifying the "resource_type" parameter as "raw", "video", or "auto", I keep encountering the error [Error : Invalid image file].

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

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

    // A function that requests a signature from my API 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,
    };
  };

Could someone please point out where I might be going wrong? Thank you.

Answer №1

The resource_type parameter is crucial in the Upload API endpoint (referred to as CLOUDINARY_UPLOAD_URL in this instance). It should not be included as part of Form parameters. Since your URL consistently uses /image/upload, the error occurs when this resource_type does not align.

To resolve this issue, consider removing the resource_type form parameter and instead adjust the path in the URL based on file type: use /video/upload for videos and audio files, or /raw/upload for non-image file types like txt or json.

Alternatively, simply set the value to /auto/upload, allowing Cloudinary to automatically determine the appropriate resource_type for each asset uploaded, eliminating the need to specify 'image', 'video', or 'raw' individually.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieve information prior to CanActivation being invoked

As I develop a web application utilizing REST to retrieve data (using Spring Boot), the server employs cookies for authenticating logged-in users. Upon user signing in, I store their information in the AuthenticationHolderService service (located in root ...

Remove an array key from a MongoDB collection

I am currently working with mongoDB and my JSON data (stored under the table name "student") appears as follows: [{ name : "John", subjects:["English", "Maths"] }, { name : "Winsel" ...

Tips for retrieving multiple independent response data in Express js app.get callback

What is the optimal way to send two independent MongoDB results in an Express application via HTTP Method? Check out this concise example to clarify: //app.js var express = require('express'); var app = express(); var testController = require(& ...

Issue with React Google Maps Api: Error occurs while trying to access undefined properties for reading 'emit'

I'm trying to integrate a map using the google-map-react API, but I keep encountering the following error: google_map.js:428 Uncaught TypeError: Cannot read properties of undefined (reading 'emit') at o.r.componentDidUpdate (google_map.js: ...

Is there a way to verify the existence of a specific error in the console?

There seems to be a conflict between a WordPress plugin or code left behind by the previous programmer, causing the WordPress admin bar to always remain visible. While no error is triggered for admins, visitors may encounter a console error. My goal is to ...

The functionality of the "this" keyword appears to be malfunctioning

I've been grappling with the concept of the this keyword in JavaScript and decided to create this script to test it out: function click(){ this.innerHTML="changed"; } However, when I tried to use it in this HTML: <button id="clicker" onclick ...

What is the best way to customize the link style for individual data links within a Highcharts network graph?

I am currently working on creating a Network Graph that visualizes relationships between devices and individuals in an Internet of Things environment. The data for the graph is extracted from a database, including information about the sender and receiver ...

Fixing PNG Fading Issue in Internet Explorer 8

I am currently utilizing the jQuery Cycle plugin to produce a fading animation effect. While this works perfectly on most browsers, I have encountered an issue with PNG files containing semi-transparent pixels in Internet Explorer 8. These partially transp ...

The render props on the child component are not appearing on the screen as expected

Recently diving into React Native, I created a stateless component designed to iterate through props that contain objects with arrays of tags. The goal was to extract and display a single tag from each array item. (Refer to the console log in the screensh ...

React: Placing a value directly at the cursor

How can I dynamically insert a selected value from a dropdown into an input field at the position of the cursor? import { useState } from "react"; import "./styles.css"; export default function App() { const [cur, setCur] = useState( ...

What is the best way to implement a dynamic mask using imask in a React

I have a question regarding the implementation of two masks based on the number of digits. While visually they work correctly, when I submit the form, the first mask is always selected. How can I resolve this issue? My solution involves using imask-react ...

Is there a way to automatically remove a video using JavaScript once it has completed playing?

This is my HTML section: <section id ="information"> <video id ="videoName" width="800" height="400" controls onplay="myAnimationPicture()""> <source src="video/videoName.mp4" ; type="video/mp4"> Your browser does not support the ...

Switching the markLine in vega lite to a markBar causes it to lose its sorting arrangement

I have created the following data visualization: data = [{"student_name": "student 0", "e": "100.15", "d": "127.81"}, {"student_name": "student 1", "e": "100.30", "d": "189.94"}, {"student_name": "student 2", "e": "100.15", "d": "105.33"}, {"student_nam ...

What is the best way to generate a new div element when the content exceeds the preset height of the current div?

CSS .page{ width: 275px; hight: 380px; overflow: auto; } HTML <div class="page">dynamic text</div> Is there a way to automatically create new div elements when dynamic text overflows past the fixed height of the init ...

Is it possible to modify CSS animations using a variable passed from typescript?

Looking for a way to streamline my animations in the .ts file so that I can use a single block of code to change the hardcoded RGB values with a variable called this.fillColor. Each animation is currently set up separately for different elements, but the ...

How can I make a method in VueJS wait to execute until after rendering?

There is a button that triggers the parse method. parse: function() { this.json.data = getDataFromAPI(); applyColor(); }, applyColor: function() { for (var i=0; i<this.json.data.length; i++) { var doc = document.getElementById(t ...

Loading slides in bxSlider using ajax

Is there a method to dynamically insert a slide into bxSlider via ajax without affecting its smooth transition? I am looking to initially display the contents of only one slide upon page load, and then have subsequent slides loaded when the next or previo ...

React encountered an unexpected end of JSON input while streaming JSON data

Currently, I am facing a challenge with streaming a large amount of data from a NodeJS server that retrieves the data from Mongo and forwards it to React. Due to the substantial volume of data involved, my approach has been to stream it directly from the s ...

Discovering the versatility of Typescript objects

I want to define a type that follows this rule: If the property container is present, then expect the property a. If the property item is present, then expect the property b. Both container and item cannot exist at the same time. The code I would expect ...

Using jQuery to reload the page following a PHP form submission

Currently facing an issue as I am trying to load the same page submitted by PHP, specifically in a comment section. After users submit their message, I want to display the existing comments along with the new one. The problem arises because I'm not u ...