Uploading Files using NodeJS and Angular Js The files will be uploaded to public/img folder. we can then run image processing on the file to convert it to several formats we want.
//Node.js app.js
/**
* Module dependencies.
*/
var express = require('express');
var routes = require('./routes');
var http = require('http');
var path = require('path');
var fs = require('fs');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.multipart()); //for uploading files
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
app.post('/upload', function (req, res) {
// get the temporary location of the file
var tempPath = req.files.file.path;
// set where the file should actually exists - in this case it is in the "images" directory
var target_path = './public/img/' + req.files.file.name;
// move the file from the temporary location to the intended location
fs.rename(tempPath, target_path, function (err) {
if (err) throw err;
// delete the temporary file, so that the explicitly set temporary upload dir does not get filled with unwanted files
fs.unlink(tempPath, function () {
if (err) throw err;
res.send('File uploaded to: ' + target_path + ' - ' + req.files.file.size + ' bytes');
});
});
});
http.createServer(app).listen(app.get('port'), function () {
console.log('Express server listening on port ' + app.get('port'));
});
Below is the angular.js component for uploading.
//inject angular file upload directives and service.
var demoApp = angular.module('demoApp', ['ngRoute']);
demoApp.directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function(){
scope.$apply(function(){
modelSetter(scope, element[0].files[0]);
});
});
}
};
}]);
demoApp.service('$fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file, uploadUrl){
var fd = new FormData();
fd.append('file', file);
console.log(fd)
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
})
.error(function(){
});
}
}]);
demoApp.controller('UploadCtrl', ['$scope', '$fileUpload',
function ($scope, $fileUpload) {
$scope.uploadFile = function(){
var file = $scope.myFile;
console.log('file is ' + JSON.stringify(file));
var uploadUrl = "/upload";
$fileUpload.uploadFileToUrl(file, uploadUrl);
};
}]);
//layout.jade
doctype html
html(ng-app="demoApp")
head
title= title
link(rel='stylesheet', href='/css/style.css')
script(src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.min.js")
script(src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular-route.js")
script(src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular-resource.js")
script(src="/js/app.js")
body
block content
//index.jade
extends layout
block content
h1= title
div(ng-controller="UploadCtrl")
div
input(type="file" name="file" file-model="myFile")
input(type="button" value="submit" ng-click="uploadFile()")
Note, this was done with the help of several tutorials which i don't have the url to post right now. I will as soon as i find them.