使用ng-file-upload和mongo gridfs

时间:2015-10-11 08:06:28

标签: javascript angularjs node.js mongodb gridfs-stream

我想将一个超过16MB的文件上传到我的数据库Mongo。 在前端部分,我使用ng-file-upload模块(https://github.com/danialfarid/ng-file-upload)。在后端,我使用connect-busboy和gridfs-stream模块

我收到以下错误: POST / api / files / 500 3.084 ms - 1992 错误:不支持的内容类型:application / json; charset = utf-8     在Busboy.parseHeaders(C:... \ node_modules \ busboy \ lib \ main.js:68:9)     在新的Busboy ...

当选择文件时,我的控制器的函数$ scope.uploadFile($ file)被调用,它使用post方法调用后端服务器api。问题似乎在api调用部分。

我有两个问题: - 我究竟做错了什么?还有更好的方法吗?

这是我的代码的样子:

前端

html page

<label class="label-form" for="image">Upload Picture:</label>
<input type="file" id="image" name="image" ngf-select="uploadFile($files)" ngf-max-size="1MB" ng-model="image" ngf-pattern="'image/*'" accept="image/*" ngf-resize="{width: 100, height: 100}" />

然后我有了我的controller.js

var appControllers = angular.module('appControllers', ['ngFileUpload']);

appControllers.controller('appUploadController',['$scope','$location','Upload', function($scope, $location, Upload){
  $scope.uploadFile = function($file) {
    Upload.upload($file)
      .then(function (resp) {
        console.log('Success ' + resp.config.data.file.name + 'uploaded. Response: ' + resp.data);
    }, function (resp) {
      console.log('Error status: ' + resp.status);
    }, function (evt) {
      var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
      console.log('progress: ' + progressPercentage + '% ' + evt.config.data.file.name);
    });
   };
}]);

然后我的service.js文件,其中api / files /的后api调用:

var appServices = angular.module('appServices',[]);

appServices.factory('Upload',['$http',function($http){
    return{
        upload : function(file){
            return $http.post('/api/files/', file);
        }
    }
}]);

返回端 现在在后端,我有我的app.js文件,api.js文件和数据库配置文件,如下所示:

api.js文件:

var Busboy = require('busboy');

app.post('/api/files',function(req,res,next){
  console.log("and the call has been successful");
  var busboy = new Busboy({
	headers: req.headers
  });

  busboy.on('error', function(err) {
    console.log(err);
  });
  
  busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
    db.uploadFile(req.files.file.name); // call the function to use gridfs	
  });

  busboy.on('finish', function() {
    console.log('finish');
  });
 }

app.js

var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var busboy = require('busboy');

var app = express();

var db = require('./app/config/database'); //load the config of the database mongolab
db.init(app);

// view engine setup - configure
app.set('view engine', 'ejs');
app.set('views', __dirname + '/views');
 
// define middleware
app.use(express.static(__dirname + '/views'));
app.use(bodyParser.json()); // support json encoded bodies
app.use(busboy());
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies
app.use(morgan('dev')); // log every request to the console

// define routes
require('./app/routes/routes')(app);
require('./app/api/api')(app, db);

app.listen(3000);

这是我的数据库配置文件

var mongoose = require('mongoose'); //library for the mongo database
var Grid = require('gridfs-stream');
var fs = require('fs');
var conn = mongoose.connection;

exports.init = function(app) {  
  //connection to the mongo database
  var  uri ="mongodb://...";
  Grid.mongo = mongoose.mongo;
  mongoose.connect(uri, {server:{auto_reconnect:true}});

  conn.once('open', function() {
    var gfs = Grid(conn.db);
    app.set('gridfs', gfs);
    console.log('connection open and the mongo db URI is' +uri);
  });
};

exports.uploadFile = function(file){
  var gfs = Grid(conn.db);
  var file_name = file.name;

  var writestream = gfs.createWriteStream({
        filename: file_name,
        mode:"w",
        content_type: part.mimetype
    });
   
    fs.createReadStream(url_image).pipe(writestream);
 
    writestream.on('close', function (file) {
        console.log(file.filename + 'Written To DB');
    });
};

1 个答案:

答案 0 :(得分:2)

我认为命名问题。 Ng文件上传使用服务名称更新,你使用你的工厂名称更新,这是一个问题 - 你使用工厂发送文件,这是一个错误。

您应该使用Ng-file-upload上传机制,因此请删除您的上传工厂。

您的代码看起来一样,因为您使用了良好的命名,只添加了url param;)

var appControllers = angular.module('appControllers', ['ngFileUpload']);

appControllers.controller('appUploadController',['$scope','$location','Upload', function($scope, $location, Upload){
  $scope.uploadFile = function($file) {
   Upload.upload({
            url: 'api/files',
            data: {file: $file}
        })
      .then(function (resp) {
        console.log('Success ' + resp.config.data.file.name + 'uploaded. Response: ' + resp.data);
    }, function (resp) {
      console.log('Error status: ' + resp.status);
    }, function (evt) {
      var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
      console.log('progress: ' + progressPercentage + '% ' + evt.config.data.file.name);
    });
   };
}]);