在 Mongoose 中使用 Multer 将文件存储到 MongoDB [英] Storing a file into MongoDB using Multer in Mongoose

查看:33
本文介绍了在 Mongoose 中使用 Multer 将文件存储到 MongoDB的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到目前为止,我已经接受了 HTML 表单中的文件,并使用 ng-file-upload 模块通过 $http.post 以 angular 形式发布.现在我想在 Mongoose 中接受这个文件并将它存储到我在 MongoLab 上托管的 NoSQL MongoDB 中.我已经阅读了这个名为 Multer 的模块,并遵循了基本文档,但到目前为止只有我.在我解释问题的开始之前,让我发布我的代码:

<小时>

我的 HTML 表单:

<字段集><legend>在此处上传文件</legend><label>在此处插入文件:</label><input type="file" ngf-select ng-model="exFile" name="file" ngf-accept="'.cs'" required><i ng-show="upForm.file.$error.required">*required</i><div class="alert" ng-show="file.$error === 'pattern'">不接受文件类型

<br/><button ng-disabled="!upForm.$valid" ng-click="uploadExercise(exFile)" class="btn btn-default">提交</button><span class="progress" ng-show="picFile.progress >= 0"><div style="width:{{exFile.progress}}%" ng-bind="picFile.progress + '%'"></div></span><span ng-show="picFile.result">上传成功</span></fieldset></表单>

<小时>

我的角度代码:

 $scope.uploadExercise = 函数(文件){控制台日志(文件);var fd = new FormData();fd.append('文件', 文件);$http.post(url+"/上传", fd,{变换请求:angular.identity,标头:{'内容类型':未定义},enctype:'multipart/form-data'}).成功(函数(){}).错误(函数(){});控制台日志(FD);};

控制台日志返回正确的文件对象.

<小时>

猫鼬到目前为止:

var mongoose = require("mongoose");var express = require("express");var multer = require('multer');var upload = multer({ dest: '上传/' });var bodyparser = require("body-parser");var app = express();mongoose.connect("连接字符串");app.use(bodyparser.json());app.post('/Upload', upload.single('solution') ,function (req, res, next) {控制台日志(req.file);});

这个 console.log 一直返回 undefined.因此,某处发生了严重错误.请帮帮我!我想在我的 Mongoose 中接收这个文件并将其存储到 MongoDB 中,我以前从未这样做过,似乎找不到任何合适的 Multer 文档或任何与我的案例相关的存储文件的体面解释.我究竟做错了什么?我应该怎么做?

解决方案

伙计,你走错了路.我已经在您之前的问题请求中解释过,Multer 用于将文件保存在文件磁盘系统中,而不是直接保存到您的数据库中.为此,您必须使用 GRIDFS.

回到您当前的问题.

app.post('/Upload', upload.single('solution') ,function (req, res, next) {控制台日志(req.file);});

这里的 upload.single('solution') - 调用函数 Upload 并且传递的文件名是 solution 但很明显它在这里不可用.

使用这种类型的格式 - Multer 的文档

var storage = multer.diskStorage({目标:函数(请求,文件,cb){cb(null, '/tmp/my-uploads')},文件名:函数(请求,文件,cb){cb(null, file.fieldname + '-' + Date.now())}})var上传=multer({存储:存储})

那里的存储部分用于提供必须保存文件的路径,文件名部分用于更改您想要的文件名.

请阅读文档,因为这会有所帮助.当我们使用第三方模块时,我们必须确认他们已经提供的信息,以便我们可以轻松使用他们的工作.

让我让你更轻松.这是现成的有效代码.

Multer 在上传文件时抛出奇怪的错误通过ng文件上传

去检查那个线程.这个问题是我提出的 - 问题是我以数组格式发送文件,就像一次发送多个文件一样.如果您不这样做,只需更改 ng-file-upload 段以使用单个上传演示示例,并且在服务器端 nodejs 代码中将 .array 替换为 .single 并且事情会以您希望它们工作的方式工作 - 假设您想使用文件磁盘系统来存储文件.

我再说一遍,这种方法不会帮助您直接将文件保存在 mongodb 中.

如果您需要进一步说明,请告诉我.

I have gotten this far to accept a file in my HTML form and post in with angular via an $http.post using the ng-file-upload module. Now I want to accept this file in Mongoose and store it into my NoSQL MongoDB hosted on MongoLab. I have read about this module called Multer and followed the basic documentation, but it only me as far. Before I explain the beginning of the problem let me post my Code:


My HTML form:

<form name="upForm">
   <fieldset>
      <legend>Upload files here</legend>
         <label>Insert File Here:</label>
         <input type="file" ngf-select ng-model="exFile" name="file" ngf-accept="'.cs'" required>
         <i ng-show="upForm.file.$error.required">*required</i>
         <div class="alert" ng-show="file.$error === 'pattern'">
              file type is not accepted
         </div>
         <br />
         <button ng-disabled="!upForm.$valid" ng-click="uploadExercise(exFile)" class="btn btn-default">Submit</button>
         <span class="progress" ng-show="picFile.progress >= 0">
         <div style="width:{{exFile.progress}}%" ng-bind="picFile.progress + '%'"></div>
         </span>
         <span ng-show="picFile.result">Upload Successful</span>
    </fieldset>
</form>


My Angular Code:

 $scope.uploadExercise = function (file) {

    console.log(file);
    var fd = new FormData();
    fd.append('file', file);
    $http.post(url+"/Upload", fd,{
        transformRequest: angular.identity,
        header:{'Content-Type': undefined},
        enctype:'multipart/form-data'
    }).success(function () { }).error(function () { });
    console.log(fd);
};

console logs return the correct file objects.


Mongoose so far:

var mongoose = require("mongoose");
var express = require("express");
var multer = require('multer');
var upload = multer({ dest: 'Uploads/' });
var bodyparser = require("body-parser");
var app = express();


mongoose.connect("connection-string");
app.use(bodyparser.json());

app.post('/Upload', upload.single('solution') ,function (req, res, next) {
    console.log(req.file);
});

This console.log keeps returning undefined. So something, somewhere went terribly wrong. Please help me out! I want to receive this file in my Mongoose and store it into the MongoDB, I have never done this before and can't seem to find any decent documentation for Multer or any decent explanation for storing files that is relevant for my case. What am I doing wrong? What should I be doing instead?

解决方案

Man you are running on the wrong path. I have already explained in your previous question request that Multer is used to save files in file disk system and not to your database directly. For that you must use GRIDFS.

Coming to your current question.

app.post('/Upload', upload.single('solution') ,function (req, res, next) {
    console.log(req.file);
});

Here the upload.single('solution') - calls a function Upload and the file name passed is solution but it is obvious enough that it isn't available here.

use this type of format - documentation of Multer

var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, '/tmp/my-uploads')
  },
  filename: function (req, file, cb) {
    cb(null, file.fieldname + '-' + Date.now())
  }
})

var upload = multer({ storage: storage })

The Storage Part there is used to give path to where your file must be saved and the file name section is used to make changes to the file name that you would like to have.

Please read the documentation because that'll help. When we use third party modules we must acknowledge the information they have already given so that we can use their work easily.

Let me make it easier for you. Here is ready made code that works.

Multer throwing weird error while uploading file via ng-file upload

Go check that thread. The question was raised by me - the problem there was I was sending files in array format, as in multiple files at once. If you are not doing that just change ng-file-upload segment to use the single upload demo example and on server side nodejs code replace .array with .singleand things will work the way you want them to work - given that you want to use file disk system to store files.

I repeat that this method wont help you to save the file in mongodb directly.

Let me know if you need any further clarification.

这篇关于在 Mongoose 中使用 Multer 将文件存储到 MongoDB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆