简体   繁体   中英

How to send mp3 file from Java Backend to frontend and play the file in the Vue.js frontend

We have a Spring Boot java Backend and a frontend in Vue.js. Backend API code calls an external API to get MP3 and Vue.js frontend calls backend API to get the mp3 file and play the same. Now sometimes the browsers are showing erratic behavior where sometimes they don't play the mp3 because of CORS issue.

Because of this, I want to download the file in the backend itself and return may be bytes to the frontend. I am very new to the frontend and wondering what would be the best way to download the mp3 from backend and in which format the mp3 file should be sent to frontend and how to convert the bytes to mp3 using javascript(vue).

Please note the files size is extremely small. The file is <5sec mp3 file, so I don't want to store the file in the server.

From Spring you can return 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;

and then get it in javascript like so:

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'jj
        .catch(e => console.log('ERROR DOWNLOADING AUDIO FILE'));

I used React and axios, but I hope you'll manqge;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM