John John - 3 months ago 29
AngularJS Question

AngularJS failed to upload file express

I am trying to upload a file to express ( so i can upload it to mongoDB later on). However, when I try to upload a file to express, i print out the response data, and it seems like nothing is getting passed in.

Im using ng-file-upload.min.js. Can anyone help me out?

script.js



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

app.controller('MyCtrl', ['$scope', 'Upload', '$timeout', function ($scope, Upload, $timeout) {
$scope.uploadFiles = function(files, errFiles) {
$scope.files = files;
$scope.errFiles = errFiles;
angular.forEach(files, function(file) {
file.upload = Upload.upload({
url: '/uploadFile',
data: {file: file}
});

file.upload.then(function (response) {
$timeout(function () {
file.result = response.data;
});
}, function (response) {
if (response.status > 0)
$scope.errorMsg = response.status + ': ' + response.data;
}, function (evt) {
file.progress = Math.min(100, parseInt(100.0 *evt.loaded / evt.total));
});
});
}
}]);


Server.js



var express = require('express');
var path = require('path'); //core module
var databaseUrl = "localhost:27017/DB"; // default env
var bodyParser = require('body-parser');
var multer = require('multer');
var storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, './uploads');
},
filename: function (req, file, callback) {
callback(null, file.fieldname + '-' + Date.now());
}
});
var upload = multer({ storage : storage}).single('userFile');

// Configure app
var app = express();

// Store all html files in views
app.use(express.static(__dirname + '/views'));
// Parses recived json input
app.use(bodyParser.json());
// Store all js in Scripts folder
app.use(express.static(__dirname + '/scripts'));

// Technology not needed but good practice, especailly when serval people are working on it
app.get('/', function (req, res) {
res.sendFile('index.html');
});

// Listen for Seach collection request


app.post('/uploadFile',function(req,res){
upload(req,res,function(err) {
if(err) {
console.log("Error uploading file");
}else{
var databaseName = "E-learn" , collection = "Uploads";
var data = req.body;
console.log("Got req:"+req);
}
});
});

// Implement a web server to listen to requests on port 4444
app.listen(5555, function(){
console.log('ready on port 5555');
});


Index.html

<!-- Page Content -->
<div class="container" ng-app="fileUpload" ng-controller="MyCtrl">
<div class="panel panel-default">
<div class="panel-heading"><strong>Upload Files</strong> <small>Bootstrap files upload</small></div>
<div class="panel-body">

<!-- Standar Form -->
<h4>Select files from your computer</h4>
<form action="" method="post" enctype="multipart/form-data" id="js-upload-form">
<div class="form-inline">
<div class="form-group">
<input name="userFile" type="file" ngf-select="uploadFiles($files, $invalidFiles)" multiple accept="image/*" ngf-max-height="1000" ngf-max-size="1MB">
</div>
<button type="submit" class="btn btn-sm btn-primary" id="js-upload-submit">Upload files</button>
</div>
</form>
<!-- Drop Zone -->
<h4>Or drag and drop files below</h4>
<div class="upload-drop-zone" id="drop-zone" ngf-drop ngf-select ng-model="files" class="drop-box"
ngf-drag-over-class="'dragover'" ngf-multiple="true" ngf-allow-dir="true"
accept="image/*,application/pdf" ngf-pattern="'image/*,application/pdf'">
Just drag and drop files here
</div>
<!-- Progress Bar
<div class="progress">
<div class="progress-bar" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 60%;">
<span class="sr-only">60% Complete</span>
</div>
</div>
-->
<!-- Upload Finished -->
<div class="js-upload-finished">
<h3>Processed files</h3>
<div class="list-group">
<ul>
<li ng-repeat="f in files" style="font:smaller"><span class="badge alert-success pull-right">{{f.name}} {{f.$errorParam}}</span>
<span class="progress" ng-show="f.progress >= 0">
<div style="width:{{f.progress}}%" ng-bind="f.progress + '%'"></div>
</span>
</li>
<li ng-repeat="f in errFiles" style="font:smaller">
{{f.name}} {{f.$error}} {{f.$errorParam}}
</li>
</ul>
{{errorMsg}}
</div>
</div>
</div>
</div>
</div>


Result
Error uploading file

Answer

As Mitchell Simoens Said multer is a good option. Im guessing you need some help writing the code. So here is an example.

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

var upload = multer({ storage : storage}).single('file');

app.post('/uploadFile',function (req,res){
  upload(req,res,function (err) {
    if (err) {
      console.log("Error uploading file"); 
    }

    var databaseName = "E-learn" , collection = "Uploads"; 
    var data = req.body;
    console.log("Got req:"+req);
  });
});