使用 ng-file-upload 和 mongo gridfs 上传文件

Upload file using ng-file-upload and mongo gridfs

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

我收到以下错误: POST /api/files/ 500 3.084 毫秒 - 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 页

<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 文件,其中 post api 调用了 api/files/:

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');
    });
};

我认为命名有问题。 Ng-file-upload 使用服务名称 Update 并且您也使用名称为 Update 的工厂,这是一个问题 - 您使用您的工厂发送文件,这是一个错误。

你应该使用 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);
    });
   };
}]);