Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
263 views
in Technique[技术] by (71.8m points)

javascript - Storing a file into MongoDB using Multer in Mongoose

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...