Skip to content

Instantly share code, notes, and snippets.

@tithi021
Last active September 18, 2016 05:58
Show Gist options
  • Save tithi021/cd162493436f66b1cc85134fdaab100e to your computer and use it in GitHub Desktop.
Save tithi021/cd162493436f66b1cc85134fdaab100e to your computer and use it in GitHub Desktop.
Photo upload by Angularjs/NodeJs using ng-file-upload module.
profile.route('/api/1.0/profile/upload/profilePhotoUpload').put(uploadFile.uploadProfilePhoto);
var uuid = require('node-uuid'),
multiparty = require('multiparty'),
fs = require('fs'),
path = require('path'),
mkdirp = require('mkdirp');
exports.uploadCoverPhoto = function(req, res, next) {
var form = new multiparty.Form();
form.parse(req, function(err, fields, files) {
var file = files.file[0];
var contentType = file.headers['content-type'];
var tmpPath = file.path;
var extIndex = tmpPath.lastIndexOf('.');
var extension = (extIndex < 0) ? '' : tmpPath.substr(extIndex);
// uuid is for generating unique filenames.
var fileName = uuid.v4() + extension;
var coverPhotoPath = path.join(__dirname, '../photos/cover-photo/');
mkdirp(coverPhotoPath, function(err) {
var fullpathName = coverPhotoPath + fileName;
// Server side file type checker.
if (contentType !== 'image/png' && contentType !== 'image/jpeg') {
fs.unlink(tmpPath);
return res.status(400).json({
success: false,
message: 'Unsupported file type'
});
}
fs.rename(tmpPath, fullpathName, function(err) {
if (err) {
return res.status(400).json({
success: false,
message: 'Image is not saved'
});
}
else {
res.status(200).send(fullpathName);
}
});
});
});
};
vm.browseCoverPhoto = function() {
angular.element('#coverPic').trigger('click');
};
// upload on file select
vm.uploadCoverPhoto = function(file) {
if (file.length) {
if (angular.isArray(file)) {
file = file[0];
}
$scope.upload = Upload.upload({
url: '/api/1.0/profile/upload/coverPhotoUpload',
method: 'put',
file: file
}).success(function(data, status, headers, config) {
vm.coverPhoto = data.data;
}).error(function(err) {
console.log(err);
});
}
};
<input type="file" id="coverPic" ngf-select="vm.uploadCoverPhoto($files)" hidden>
<div>
<img src="{{vm.coverPhoto}}">
<div ng-click="vm.browseCoverPhoto()">
<i class="fa fa-camera custom-icon" aria-hidden="true"></i>
</div>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment