【问题标题】:How can i upload audio file to Cloudinary with Node.js?如何使用 Node.js 将音频文件上传到 Cloudinary?
【发布时间】:2018-10-18 04:11:13
【问题描述】:

我非常需要帮助,将这个音频文件上传到我已经有好几天的云端问题。我尝试了很多次让它工作,但我仍然在挣扎。我是初学者后端开发人员,因此请提供任何帮助。

它是一个 mp3 播放器应用程序。当我上传歌曲时,标题会保存在数据库中,但 音频 不是。

This is the MP3 PLAYER page screenshot. It shows the title being saved and rendered from DB but not the audio file.

音频上传表单

   <form class="ui form" action="/albums/<%= album._id %>/songs" method="POST" enctype="multipart/form-data">
            <div class="field">
                <label>Song Title:</label>
                <input type="text" id="title" name="song[title]" placeholder="song title...." required>
            </div>
            <div class="field">
                <label>Song file:</label>
                <input type="file" id="song" name="audio" accept="audio/*" required>
            </div>
            <div class="field">
                <input class="fluid ui green button" type="submit" id="submit" value="Enter">
            </div>
            <a href="/albums/<%= album._id %>" class="ui small orange button exit-btn">Exit</a>
     </form>

歌曲模型

var mongoose = require("mongoose");

//Album Schema
var audioSchema = new mongoose.Schema({
   title: String,
   audio: String,
   date: {type: Date, default: Date.now()}

});

//exporting the Schema
module.exports = mongoose.model("Audio", audioSchema);

后端代码/ROUTE

var express             = require("express"),
    router              = express.Router({mergeParams: true}),
    middleware          = require("../middleware"),
    Album               = require("../models/album"),
    Song                = require("../models/songs"),
    multer              = require("multer")

var storage = multer.diskStorage({
  filename: function(req, file, callback) {
    callback(null, Date.now() + file.originalname);
  }
});
//uploader
var upload = multer({ storage: storage});
var cloudinary = require('cloudinary');
cloudinary.config({ 
   cloud_name: 'proccess.env.CLOUDINARY_NAME',
   api_key: process.env.CLOUDINARY_API_KEY, 
   api_secret: process.env.CLOUDINARY_API_SECRET
});

//Songs new Route
router.get("/albums/:id/songs/new", middleware.isLoggedIn, function(req, res) {
  //find Album by id
  Album.findById(req.params.id, function(err, album) {
      if(err) {
          console.log(err);
      } else {
          res.render("songs/new", {album: album});
      }
  });
});
//Song POST route
router.post("/albums/:id/songs", middleware.isLoggedIn, upload.single("audio"), function(req, res) {
    cloudinary.uploader.upload(req.file.path, function(result) {
        // add cloudinary url for the mp3 to the album object under audio property
        req.body.song.audio = result.secure_url;
        //find Album by ID
        Album.findById(req.params.id, function(err, album) {
            if(err) {
                console.log(err);
                res.redirect("/albums/" + req.params.id);
            } else {

                //Creating Album and saving it to DB
                Song.create(req.body.song, function(err, song) {
                    if(err) {
                        console.log("Opps something went wrong!" + err);
                        res.redirect("back");
                    } else {
                        //save the song to DB
                        song.save();
                        //this saves the songs object inside 
                        album.songs.push(song);
                        //save album
                        album.save();
                        res.redirect("/albums/" + album._id);
                    }
                });

            }

        });
    });    

});


module.exports = router;

【问题讨论】:

  • 寻求调试帮助的问题(“为什么这段代码不起作用?”)必须包括所需的行为、特定的问题或错误以及必要的最短代码 重现它在问题本身。没有清晰的问题陈述的问题对其他读者没有用处。见:How to create a Minimal, Complete, and Verifiable example.

标签: html node.js mongodb express mongoose


【解决方案1】:

这是因为您需要使用 MongoDB 中的 GridFS 来存储文件中的数据。 https://docs.mongodb.com/manual/core/gridfs/#use-gridfs

当您使用 Mongoose 时,请查看此模块:https://www.npmjs.com/package/mongoose-gridfs

mongoose-gridfs 模块包装了 gridfs-stream 模块,似乎适合二进制数据上传。如果你愿意,你仍然可以按照本教程自己做:http://niralar.com/mongodb-gridfs-using-mongoose-on-nodejs/

【讨论】:

  • 谢谢尼古拉斯。但是我已经阅读了很多关于 gridFS 的内容。我只是无法用我的代码实现它。我使用其他开发人员的示例尝试了几次,但我无法让它工作......
猜你喜欢
  • 2020-05-18
  • 2018-04-08
  • 2021-05-10
  • 2018-02-02
  • 2023-04-11
  • 1970-01-01
  • 2013-05-23
  • 2017-06-17
  • 2016-04-28
相关资源
最近更新 更多