我使用 mongodb 、 gridfs 、 multer 来存储音频文件。并且需要通过axios在reactjs前端显示音频文件。
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);
});
});
在前端显示音频文件
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>
)
}
这是文件请求
{
_id: 60774f8560de1713d4b06234,
length: 11756413,
chunkSize: 261120,
uploadDate: 2021-04-14T20:25:25.300Z,
filename: '379500b35576a4c49792718aebfc27ef.mp3',
md5: '36d8d712eb886859b07952e49d4de6a6',
contentType: 'audio/mpeg'
}
在邮递员中,它显示了一个音频文件,并且工作正常。我需要在前端显示它。
谢谢你。