Transforming sound data into a file format for submission to the backend system (without the need to store it on the

UPDATE: I found a few minor errors in this post, which have been fixed and resolved some of the issues. The other half of the problem is addressed in the accepted answer.

...

I am currently capturing microphone audio on the client side (using Nuxt/Vue) and my goal is to transfer it to my backend (Strapi). I have a MediaRecorder set up, which adds the data to my recordingFile array when the recording stops. This part is functioning correctly, as I can play back the recording using the embedded player after it is finished.

Here is the HTML snippet:

<audio
  id="localaudio"
  ..
></audio>

JavaScript code:

recorder = new MediaRecorder(mediaStream);

...     

recorder.addEventListener("dataavailable", function(e) { 
        document.querySelector("#localaudio").src = URL.createObjectURL(e.data); //add it to the player element on the page for playback
        recordingFile.push(e.data); // pushing to array recordingFile
      });

However, I am encountering problems when attempting to upload the audio to my Strapi backend. I suspect the issue lies in trying to upload a blob when Strapi is expecting a file.

  let blob = new Blob(recordingFile, { type: "audio/ogg" });

  const data = {
    "user" : "test",
    "files.File" : blob //prefix is Strapi convention
  };

  const formData = new FormData();
  formData.append('data', JSON.stringify(data));

  axios({
    method: "post",
    url: "http://localhost:1337/recordings",
    data: formData,
    headers: {
      "content-type": `multipart/form-data;`
    }
  })

I get a positive response and a new entry with user="test", but the file field remains empty. I attempted sending the file URL (URL.createObjectURL(..)) instead of the blob itself, but it did not work either.

I am referencing the Strapi documentation, but it primarily deals with files from the filesystem, not blobs generated in the browser.

Any insights?

UPDATE: recording.settings.json:

{
  "kind": "collectionType",
  "collectionName": "recordings",
  "info": {
    "name": "Recording"
  },
  "options": {
    "increments": true,
    "timestamps": true,
    "draftAndPublish": true
  },
  "attributes": {
    "File": {
      "model": "file",
      "via": "related",
      "allowedTypes": [
        "images",
        "files",
        "videos"
      ],
      "plugin": "upload",
      "required": false
    },
    "name": {
      "type": "string"
    }
  }
}

Answer №1

The recommended approach in the documentation is to attach the file or blob (either one will suffice) to the FormData instance instead of the data object.

let blob = new Blob(recordingData, { type: "audio/mp3" });
let file = new File([blob], 'recording.mp3');

const data = {
  "user" : "admin",
};

const formData = new FormData();
formData.append('files.audio', file);
formData.append('data', JSON.stringify(data));

Answer №2

It seems that when sending data through formData, it's best not to include a content-type in the request headers.

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

From JSON to JavaScript transformations

Currently, I am attempting to utilize JSON with data retrieved from the server by implementing this PHP script: include("db_connect.php"); mysql_connect($host,$username,$password); @mysql_select_db($database) or die( "Unable to select database"); $resu ...

Implementing VueJS on the Google Cloud Platform

Currently, I am developing a web application using Vue CLI 3 and I have configured it with presets like babel, PWA, Vue Router, and css preprocessors. My goal is to deploy this application on Google Cloud's App Engine. However, I am facing an issue in ...

To ensure the next line only runs after the line above has finished executing, remember that the function is invoked in HTML

my.component.html <button (click)="refresh()">Refresh</button> my.component.ts refresh() { let self = this; self.isRefresh = true; //1st time self.getfun().then(() => { self.isRefresh = false; ...

Tips for utilizing New FormData() to convert Array data from an Object for executing the POST request with Axios in ReactJs

When working on the backend, I utilize multer to handle multiple file/image uploads successfully with Postman. However, when trying to implement this in ReactJS on the frontend, I find myself puzzled. Here's a sample case: state = { name: 'pro ...

Exploring javascript Object iteration with arrays using Python

When users click the "done" button on a text box, all input is stored in an associative array and sent to a Python method. The data is then converted to JSON before being sent via AJAX: $.ajax({ url: "http://127.0.0.1:6543/create_device", ...

"Failure encountered while trying to fetch JSON with an AJAX request

I am facing an issue with an ajax request. When I make the request with the property dataType: 'json', I get a parsererror in response. My PHP function returns the data using json_encode(), can someone assist me? On the other hand, when I make th ...

What is the best way to combine the elements within an array with the elements outside of the array in order to calculate their sum?

The goal is to create a function that determines the winner using two input integers. The function should return the first input if it is greater than the second input. function determineWinner(a, b) { let result = [] for (let i = 0; i < 3; i++) ...

Is it possible to remove content from a Content Editable container?

JSFiddle <div contenteditable="true"> <p>Trying out editing capabilities of this paragraph.</p> <figure> <img src="http://www.keenthemes.com/preview/metronic/theme/assets/global/plugins/jcrop/demos/demo_files/ima ...

I'm experiencing an issue where using .innerHTML works when viewing the file locally, but not when served from a web server. What could be causing this discrepancy?

Utilizing mootool's Request.JSON to fetch tweets from Twitter results in a strange issue for me. When I run the code locally as a file (file:// is in the URL), my formatted tweets appear on the webpage just fine. However, when I serve this from my loc ...

AngularJS allows for versatile filtering of objects and arrays using checkboxes

I am looking to implement a filter functionality similar to the fiddle mentioned in the first comment below. However, I do not want to capture the checkboxes category from ng-repeat. Instead, I only want to input the checkboxes' value and receive the ...

A guide to presenting array data retrieved from an Ajax call within HTML using Laravel 4.1

I have an AJAX call to a controller that returns array data to my view. I want to display this array data in HTML upon clicking, but I'm not sure how to do it yet. Here's what I have so far: AJAX Call: request = $.ajax({ url: "/fans/ ...

Guide: Passing and reading command line arguments in React JavaScript using npm

When launching the react application, I utilize npm start which is defined in package.json as "start": "react-scripts start -o". Within the JavaScript code, I currently have: const backendUrl = 'hardCodedUrl'; My intention ...

A glitch occurred while attempting to load content dynamically onto an HTML page using Ajax

Attempting to dynamically load content into an HTML div is causing issues for me. Whenever I try to do so, an error pops up: Syntax error HOME. (this is the expected visible content within the div). HTML: Navigation bar: <li><a href="#" onclick= ...

There appears to be an issue with Mongoose Unique not functioning properly, as it is allowing

Below is the complete code snippet I am using to validate user data: import { Schema, model } from 'mongoose'; import { User } from './user.interface'; const userSchema = new Schema<User>({ id: { type: Number, required: ...

What is the proper way to assign an array of objects to an empty array within a Vue component?

I'm currently working on my first Laravel project using Vue components. My setup includes Laravel 8.x and Vue 2.x running on Windows 10. I came across a helpful video tutorial that I'm trying to follow, but some aspects aren't quite working ...

Using Jquery to insert error messages that are returned by PHP using JSON

I am attempting to utilize AJAX to submit a form. I send the form to PHP which returns error messages in Json format. Everything works fine if there are no errors. However, if there are errors, I am unable to insert the error message. I am not sure why th ...

Using Webdriver to dynamically enable or disable JavaScript popups in Firefox profiles

I am currently working on a test case that involves closing a JavaScript popup. The code functions correctly in a Windows environment, but when I try to deploy it on a CentOS based server, I encounter the following error: Element is not clickable at point ...

`The functionalities of classList.add and classList.remove aren't behaving as anticipated.`

I'm currently working on a list of items (ul, li) that have a class applied to them which adds a left border and bold highlight when clicked. My goal is to reset the style of the previously clicked item back to its original state when a new item is c ...

Utilizing Node.js with Redis for organizing data efficiently

Currently, I am in the process of configuring a Redis cache system for storing incoming JSON data in a specific format. My goal is to create an ordered list structure to accommodate the large volume of data that will be stored before eventual deletion. Th ...

`How can a child component in Next.js send updated data to its parent component?`

Currently diving into Next.js and tinkering with a little project. My setup includes a Canvas component alongside a child component named Preview. Within the Preview component, I'm tweaking data from the parent (Canvas) to yield a fresh outcome. The b ...