我有一个目录,用户上传的所有歌曲都会上传。我已经使用mongodb这个应用程序,mongodb工作正常,但我想使用 src url like uploads / something to songs / user / songname我试过使用Router.get,如Controller.js所示 但是当我使用它时,我有内部500错误,请让我知道我犯了错误。
controller.js
Router.get('/songs/:artist/:song', (req, response) => {
console.dir(req.query)
let file = './uploads/01-Whole Lotta Love.mp3'
var stat = FileSystem.statSync(file)
response.setHeader('Content-Type', 'audio/mpeg');
response.setHeader('Content-Length', stat.length);
fs.createReadStream(file).pipe(response);
})
app.js
app.use(Express.static(path.join(__dirname, 'uploads')));
profile.ejs
<table border="1">
<% artist.songs.forEach((song) => { %>
<tr>
<td> <%= song.song %> </td>
<td>
<audio controls>
<source src="./songs/<%= artist.artistName+ '/' + song.audioPath %>" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
</td>
<td>3k listens</td>
<td>2k likes</td>
<td>2k comments</td>
</tr>
<% }) %>
</table>
就像我为 songs / anyusername / songname 所写的那样,将使用目录上传/歌曲名称
提前谢谢你:)答案 0 :(得分:2)
尝试使用此代码,在浏览器中打开:http://host:port/song/foo/bar
并在评论中写下你得到的:
const
fs = require('fs'),
path = require('path'),
bufferSize = 100 * 1024;
Router.get('/songs/:artist/:song', (req, res) => {
let
file = '01-Whole Lotta Love.mp3';
file = path.join(__dirname, 'uploads', file);
console.log('Piping file:', file); // check if path is correct
fs.stat(file,
(err, stat) => {
if(err) {
return res.status(500).send(err); // output error to client
}
res.writeHead(200, {
'Cache-Control': 'no-cache, no-store, must-revalidate',
'Pragma': 'no-cache',
'Expires': 0,
'Content-Type': 'audio/mpeg',
'Content-Length': stat.size
});
fs.createReadStream(file, {bufferSize}).pipe(res);
});
})