I used mongodb , gridfs ,multer to store the audio file. And need to show the audio file in reactjs frontend through axios.
app.get('/songs/getsong/:filename', (req, res) => {
console.log(req.params.filename);
const file = gfs
.find({
filename: req.params.filename
})
.toArray((err, files) => {
if (!files || files.length === 0) {
return res.status(404).json({
err: "no files exist"
});
}
gfs.openDownloadStreamByName(req.params.filename).pipe(res);
console.log(files)
return res.status(200);
});
});
Display audio file in frontend
import React, { useEffect ,useState} from 'react'
import Header from '../header/Header';
import "./home.css"
import axios from 'axios';
export default function Home(){
const [audiofile , setAudioFile] = useState()
axios.get('http://localhost:8000/songs/getsong/379500b35576a4c49792718aebfc27ef.mp3')
.then((res) => {
console.log(res);
setAudioFile(res)
}).catch((error) => {
console.log(error)
});
return (
<div>
<Header />
<form action="http://localhost:8000/songs/upload" method="post" enctype="multipart/form-data">
<h1>File Upload</h1>
<input id="file" type="file" accept="audio/*" name='file' />
<input type="submit" />
</form>
<audio
controls
src={audiofile}>
Your browser does not support the
<code>audio</code> element.
</audio>
</div>
)
}
this is the file request
{
_id: 60774f8560de1713d4b06234,
length: 11756413,
chunkSize: 261120,
uploadDate: 2021-04-14T20:25:25.300Z,
filename: '379500b35576a4c49792718aebfc27ef.mp3',
md5: '36d8d712eb886859b07952e49d4de6a6',
contentType: 'audio/mpeg'
}
In postman it showed a audio file and it works fine. I need to show it on frontend.
Check Postman response ss here
Thank you.
Locally, you can use the HTML5 Audio tag to play the audio, feed src with URL of the audio and , that's it.