Guide for sending an mp3 file from a Java backend to the frontend and playing it within a Vue.js frontend application

We currently have a Spring Boot java Backend paired with a Vue.js frontend. The backend's API code utilizes an external API to fetch MP3 files, which are then accessed by the frontend through calls to the backend API for playback. However, there have been instances of browsers exhibiting inconsistent behavior where they fail to play the MP3 due to CORS issues.

To address this issue, my intention is to have the backend handle the file downloading process and return bytes to the frontend instead. As someone who is fairly new to frontend development, I am interested in knowing the most effective way to download the MP3 from the backend, the optimal format for sending the MP3 file to the frontend, and how to convert these bytes into playable MP3 files using JavaScript (specifically within Vue).

It should be noted that the size of the files is extremely small, with the MP3 files being less than 5 seconds in duration, and therefore there is no need to store the files on the server.

Answer №1

Spring allows you to retrieve an array of bytes:

File f = new File("/path/to/the/file");
byte[] file = Files.readAllBytes(f.toPath());

HttpHeaders headers = new HttpHeaders();
headers.set("Content-Disposition", "attachment; filename=\"" + f.getName() +".wav\"");
ResponseEntity<byte[]> response = new ResponseEntity(file, headers, HttpStatus.OK);

return response;

You can then access it in javascript as follows:

import fileDownload from 'js-file-download';

const { data } =  await axios.get(`http://api.url`, {
        responseType: 'arraybuffer',
        headers: { 'Accept': '*/*', 'Content-Type': 'audio/wav' }
    }).then(resp => resp);
    const blob = new Blob([data], {
        type: 'audio/wav'
    })
    const url = URL.createObjectURL(blob);

    fetch(url)
        .then(res => res.blob())
        .then(blob => fileDownload(blob, 'your_filename'))
        .catch(e => console.log('ERROR DOWNLOADING AUDIO FILE'));

I utilized React and axios for this implementation, but I believe you'll handle it well ;)

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

The object prototype can only be an instance of an Object or null; any other value will

While attempting to create a codesandbox in order to replicate a bug, I encountered an additional issue. You can view my codesandbox here: https://codesandbox.io/s/vue-typescript-example-o7xsv The error message states: Object prototype may only be an ...

Include two arguments when making a $http POST request

I am facing a situation where a single property can have multiple images, but each image can only be assigned to that one property (one-to-many relationship with propertyId as foreign key). In the HTML, I am fetching the propertyId and passing it along wi ...

Applying VueJS filters to refine object values

Is there a way to verify if the value of "startAt" is present in an object and return its corresponding ID? Here is the object in question: [{ "id": "1234567", "createTimestamp": "2020", "name": { "action": "", "allDay": false, "categor ...

Is there a way to allocate a prop to data just once?

I need assistance with an element <input type="text" class="text-[16px] text-light-text bg-main-background p-[11px]" name="email" ref="email" ...

Inconsistent CSS3 transitions behavior in Firefox 4

I have been playing around with some css3 transitions and created a slider test. It works perfectly in webkit browsers, but I have noticed an issue in Firefox 4. When clicking on the left link for the first time, the slider is supposed to slide to the left ...

Guide to positioning the highlighted image in a lightbox gallery: Aligning the active image in the

Hey there, I have implemented the Lightbox gallery feature in my Django application. The gallery functions such that when a user clicks on an image, it opens up the gallery with the selected image displayed prominently, along with the functional icons for ...

Matrix calculation for bone orientation towards an object in Three.js

I am encountering issues with calculating the orientation of a bone to "look at" an object. The lookAt function is not functioning as expected for me. This could be due to the fact that the bone's matrix is an identity matrix in local space, so the de ...

CSS Only Sidebar Dropdown (without using Bootstrap)

I want to create a sidebar with collapsible dropdown options and smooth animations using only pure css/js/html/jquery, without relying on bootstrap like I did in the past. Here is an example of what I created previously with bootstrap: Now, as a challenge ...

Using html and the javascript library 'turn.js' to make an interactive flipbook

I'm trying to use the turn.js library to create a flipbook. Here is the code I have been using, but it doesn't seem to be working correctly for me. It currently works fine on jsfiddle and you can see it here [text]http://jsfiddle.net/xd7sh59p/ W ...

unable to make a request to the express server with axios

I am in the process of developing a chat application similar to whatsapp. One of the key features I'm working on is that when a user clicks on another person's name, their chats will be displayed. However, currently, I'm facing an issue wher ...

Experiencing difficulties when uploading information to an API in a React JS application

Trying to Send Data via React to Contact Form API Having issues trying to send input data through the API when clicking submit button. The error encountered is that the API call should look like this Example Link However, it calls in a different way Diff ...

What could be causing the Next.js error: WEBPACK_IMPORTED_MODULE function not being recognized?

I've hit a roadblock with an issue I can't seem to solve. I'm exporting a function that is supposed to provide the current authenticated user object, if available. I then use this user object to determine whether to add a navigation link. De ...

Guide on incorporating the Chain Pattern alongside the Self Revealing Module Pattern within JavaScript

I have come across the following code snippet: filtersManager = (function ($) { var that = this; function initialize() { // some tasks return that; }; function execute() { // some tasks return that; ...

AngularJS Search Filtering Error: [ng:areq]

Trying to implement a search filter in my AngularJS application, but encountering an error in the Chrome console: Error: [ng:areq] Below is the code snippet: <div id="notebooks" ng-controller="NotebookListCtrl"> <input type="text" id="query" n ...

Unable to make changes while state transition is in progress

I want to update the state value based on the result of a promise method. To have optimistic updates, I set the state value before an asynchronous operation. If the operation fails, the state is reset. componentWillMount(){ this.setState({notify: this ...

What steps should I take to insert a divider in a dropdown menu?

I am attempting to enhance my dropdown menu by incorporating a separator using the following code: <li class='divider'></li> Below is my HTML code with the separator included: <ul class="dropdown-menu dropdown-menu-right" id="ul ...

Managing memory in Three.js

I am facing an issue with managing memory in my large scene that consists of Mesh and MorphAnimMesh objects. I have tried to free up memory by removing these meshes, but it seems like the memory usage remains unchanged. for ( var i = scene.children.length ...

Determine the return type of a function based on a key parameter in an interface

Here is an example of a specific interface: interface Elements { divContainer: HTMLDivElement; inputUpload: HTMLInputElement; } My goal is to create a function that can retrieve elements based on their names: getElement(name: keyof Elements): Elemen ...

Linking two div elements together with a circular connector at the termination point of the line

I am currently working on designing a set of cards that will showcase a timeline. I envision these cards to be connected by lines with circles at each end, for a visually appealing effect. At the moment, I have created the cards themselves but I am struggl ...

Testing with mount in React Enzyme, the setState method does not function correctly

I've been experimenting with testing this code block in my React App using Jest and Enzyme: openDeleteUserModal = ({ row }: { row: IUser | null }): any => ( event: React.SyntheticEvent ): void => { if (event) event.preventDefault(); ...