Last active
March 14, 2018 05:58
-
-
Save keithics/bf0e13feaee5631fa936b7b203029cd4 to your computer and use it in GitHub Desktop.
Uploading images - MEAN STACK
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//routes | |
app.route('/api/teams/logo').all() | |
.post(teams.upload).all(teamsPolicy.isAllowed) | |
//server.controller | |
//sharp = require('sharp') :: http://sharp.dimens.io/ | |
exports.upload = function (req, res) { | |
var upload = multer(uploadConfig).single('photo'); | |
upload(req, res, function (uploadError) { | |
if (uploadError) { | |
return res.status(400).send({ | |
message: 'Error uploading file' | |
}); | |
} else { | |
var file = './public/uploads/' + req.file.filename; | |
sharp(file) | |
.toFormat(sharp.format.jpeg) | |
.resize(250, 250) | |
.toFile('./public/uploads/' + req.file.filename + '.jpg', function (err) { | |
if (err) { | |
fs.unlinkSync(req.file.path); | |
return res.status(400).send({ | |
message: 'Error uploading file' | |
}); | |
} | |
else { | |
fs.unlinkSync(req.file.path); | |
req.file.url = req.protocol + '://' + req.headers.host + '/uploads/' + req.file.filename + '.jpg'; | |
res.jsonp(req.file); | |
} | |
}); | |
} | |
}); | |
}; | |
//HTML | |
/* | |
<input type="file" nv-file-select uploader="uploader" ng-if="!uploader.isUploading"/> | |
<span ng-if="uploader.isUploading">Uploading.. pls wait..</span> | |
<img ng-show="done" ng-src="{{image.url}}" class="col-md-8" alt=""/> | |
*/ | |
//bower | |
//"angular-file-upload": "1.1.5" | |
//Angular | |
'use strict'; | |
// Teams controller | |
angular.module('uploads').controller('UploaderController', | |
['$scope', '$stateParams', '$location', 'Authentication', 'FileUploader', '_', | |
function ($scope, $stateParams, $location, Authentication, FileUploader, _) { | |
$scope.authentication = Authentication; | |
/** uploader **/ | |
$scope.done = false; | |
var uploader = $scope.uploader = new FileUploader({ | |
autoUpload: true, | |
url: '/api/teams/logo', | |
alias: 'photo', | |
queueLimit: 1, | |
removeAfterUpload: true | |
}); | |
uploader.onErrorItem = function (fileItem, response, status, headers) { | |
$scope.message = {type: 'error', title: 'Error', message: response.message}; | |
}; | |
uploader.onSuccessItem = function (fileItem, response, status, headers) { | |
$scope.team.logo = response; | |
$scope.image = response; | |
}; | |
uploader.onCompleteAll = function () { | |
$scope.done = true; | |
$scope.message = null; | |
}; | |
} | |
]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment