使用Mongoose在均值堆栈应用程序中上传和检索文本/pdf/img文件



我一直在尝试编写一件代码,在该代码中,用户创建动态URL,通过单击页面上的按钮上传文件,用户还可以下载当他/她再次访问相同的URL时,以相同格式的相同文件。该概念非常类似于CL1P,并代替文本。

我对此进行了很多答案,但是我找不到有关如何在Angular Controller 中接受该文件的任何帮助,然后传递到后端(Node.js代码),其中可以使用 mongoose 将文件保存在MongoDB数据库上,并且可以从MongoDB数据库中检索相同的文件。另外,我希望将完整的文件保存在数据库中,而不仅仅是文件的路径/目的地。

请帮助。

到目前为止,我所拥有的只是 -

<div ng-controller="main">
<input type="file" name="myFile" id="file" />
<button type="submit">Upload</button>
</div>

ps :不要要求我使用gridfs,在数据超过16MB时,我的文件大小不会超过2〜3MB。

我对Angular不太熟悉。但是,我可以提示后端。

Model.js

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var schema = new Schema({
  image: {data: Buffer, contentType: String},
    .
    .
});
module.exports = mongoose.model('Model', schema);   

rout.js

var Model = require('path/to/model');
// POST: called by uploading form
router.post('/add', function (req, res, next) {
  var model = new Model();
  fs.readFile(req.body.myFile, function (err, data) {
    model.image.data = data;
    // get extension
    model.image.contentType = req.body.myFile.split('.').pop();
        .   
        .
    model.save(function (err, model) {
      if(err) throw err;
      res.status(201).json(model);
    });
  });
});
// GET image by model id: subsequence retrieval
router.get('/:id/image', function (req, res, next) {
  var modelId = req.params.id;
  Model.findById(modelId, function (err, model) {
    res.contentType(model.image.contentType);
    res.json(model.image.data);
  });
});

我使用https://github.com/expressjs/multer为我工作,尤其是如果您想将其存储在其他任何地方,

和https://github.com/nervgh/angular-file-upload在客户端,如果您使用Angular 1。

最新更新