简体   繁体   English

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

[英]Upload file using ng-file-upload and mongo gridfs

I want to upload a file that is more than 16MB to my database Mongo. 我想将超过16MB的文件上传到数据库Mongo。 On the front end part, I use ng-file-upload module ( https://github.com/danialfarid/ng-file-upload ). 在前端部分,我使用ng-file-upload模块( https://github.com/danialfarid/ng-file-upload )。 On the back-end side, i use connect-busboy and gridfs-stream modules 在后端,我使用connect-busboy和gridfs-stream模块

I get the following error: POST /api/files/ 500 3.084 ms - 1992 Error: Unsupported content type: application/json;charset=utf-8 at Busboy.parseHeaders (C:...\\node_modules\\busboy\\lib\\main.js:68:9) at new Busboy... 我收到以下错误: 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上...

When the file is selected, the function $scope.uploadFile($file) of my controller is called which is calling a backend server api with a post method. 选择文件后,将调用控制器的$ scope.uploadFile($ file)函数,该函数使用post方法调用后端服务器api。 The issue seems to be on the api call part. 问题似乎在api调用部分。

I have 2 questions: - what am I doing wrong? 我有两个问题:-我做错了什么? and is there a better way to do it? 有更好的方法吗?

Here how my code looks like: 我的代码如下所示:

front-end 前端

html page 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}" /> 

then I have my controller.js 然后我有我的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); }); }; }]); 

then my service.js file where the post api call to api/files/ is made: 然后我的service.js文件在其中对api / files /进行了api调用:

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

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

Back-end Now on the backend-side, I have my app.js file, the api.js file and the database configuration file as below: 后端现在在后端,我有我的app.js文件,api.js文件和数据库配置文件,如下所示:

the api.js file: 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 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); 

here is my database config file 这是我的数据库配置文件

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

I think problem with naming. 我认为命名有问题。 Ng-file-upload use service name Update and you use your factory with name Update too and this is a problem - you use your factory to send file and this is a mistake. Ng-file-upload使用服务名称Update,并且您也使用名称为Update的工厂,这是一个问题-您使用工厂发送文件,这是一个错误。

You should use upload mechanism from Ng-file-upload, so remove your Upload Factory. 您应该从Ng-file-upload中使用上传机制,因此请删除您的Upload Factory。

Your code will be look the same, because you use good naming, you add only url param;) 您的代码将看起来一样,因为使用了良好的命名,所以只添加了url参数;)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM