最近我问了一个关于将通过multer上传的文件保存到mongodb的问题。我能够让它工作,但我无法在我的index.ejs中显示该文件。例如,我上传了一个音乐文件,当我试图通过在路径周围包装音频标签在index.ejs中显示它时,它显示音频控件,但播放按钮被禁用,音量图标上有一个斜杠。请看我的代码。
routes.js
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './uploads/');
},
filename: function (req, file, cb) {
var originalname = file.originalname;
var extension = originalname.split(".");
filename = Date.now() + '.' + extension[extension.length-1];
cb(null, filename);
}
});
router.post('/', multer({storage: storage, dest: './uploads/'}).single('uploads'), function(req,res){
var music = new Music ({
fieldname: req.file.fieldname,
originalname: req.file.originalname,
encoding: req.file.encoding,
mimetype: req.file.mimetype,
destination:req.file.destination,
filename: req.file.filename,
path: req.file.path,
size: req.file.size
})
music.save(function(err){
if (err){console.log(err)}
else {
res.redirect('/');
}
})
});
音乐模型
var mongoose = require('mongoose');
var musicSchema = new mongoose.Schema({
fieldname: String,
originalname: String,
encoding: String,
mimeptype: String,
destination: String,
filename: String,
path: String,
size: Number,
created_at: Date,
updated_at: Date
});
var Music = mongoose.model('Music', musicSchema);
module.exports = Music;
index.ejs
<form action="/" enctype="multipart/form-data" method="post">
<input type="text" name="title">
<input type="file" name="uploads">
<input type="submit" value="Uploads">
</form>
<% for(var i = 0; i < musics.length; i++){ %>
<p> <%= musics[i].originalname %> </p>
<audio autoplay="autoplay" controls="controls">
<audio controls="controls">
<source src="<%= musics[i].path %>"/>
</audio>
<%}%>
这是我的mongo db中的数据
{ "_id" : ObjectId("576e27051ca343b201992472"), "created_at" : ISODate("2016-06-25T06:39:02.004Z"), "updated_at" : ISODate("2016-06-25T06:39:02.004Z"), "fieldname" : "uploads", "originalname" : "Trance - Tricky Tricky.mp3", "encoding" : "7bit", "destination" : "./uploads/", "filename" : "1466836741963.mp3", "path" : "uploads/1466836741963.mp3", "size" : 3818213, "__v" : 0 }
答案 0 :(得分:0)
尝试更改
<audio autoplay="autoplay" controls="controls">
<audio controls="controls">
<source src="<%= musics[i].path %>"/>
</audio>
to
<audio autoplay="autoplay"controls="controls">
<source src="<%= musics[i].path %>"/>
</audio>