i want to know, how to use upload files code in sails using angular upload
this is code for angular
var app = angular.module('app', ['angularFileUpload']);
app.controller('ImageCtrl', ['$scope', '$upload', function ($scop
e, $upload) {
$scope.$watch('files', function () {
$scope.upload($scope.files);
});
$scope.upload = function (files) {
window.alert(JSON.stringify(files));
if (files && files.length) {
for (var i = 0; i < files.length; i++) {
var file = files[i];
$upload.upload({
url: '???????',
fields: {
'username': $scope.username
},
file: file
}).progress(function (evt) {
var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
console.log('progress: ' + progressPercentage + '% ' +
evt.config.file.name);
}).success(function (data, status, headers, config) {
console.log('file ' + config.file.name + 'uploaded. Response: ' +
JSON.stringify(data));
});
}
}
};
}]);
in above code , what i should give url ? , my requirement is, i want to upload files in locally using sails mongodb.
Any one please share the server side nodejs code..
Sails have built-in streaming file uploads utility called skipper. In general you can upload files from angular to any sails endpoint. Then you just need to perform something like this in your controller:
req.file('avatar').upload(function (err, uploadedFiles){
if (err) return res.send(500, err);
return res.send(200, uploadedFiles);
});
You can also pass skipper options:
req.file('avatar').upload({
// ...any other options here...
}, ...);
If you aplication should upload files frequently I would recommend you to create service for this based on skipper API.
Related
I tried following this link https://ciphertrick.com/2015/12/07/file-upload-with-angularjs-and-nodejs/ but got error
Node version is 4.4.7, modulerr error in ngFileUpload
For file upload in app.js
var multer = require('multer');
var storage = multer.diskStorage({ //multers disk storage settings
destination: function (req, file, cb) {
cb(null, '../../../../uploads/')
},
filename: function (req, file, cb) {
//var datetimestamp = Date.now();
// cb(null, file.fieldname + '-' + datetimestamp + '.' + file.originalname.split('.')[file.originalname.split('.').length - 1])
cb(null, file.originalname)
}
});
var upload = multer({ //multer settings
storage: storage
}).single('file');
API path that will upload the files
app.post('/upload', function (req, res) {
upload(req, res, function (err) {
console.log("inside upload");
if (err) {
console.log("inside upload err");
res.json({ error_code: 1, err_desc: err });
return;
}
res.json({ error_code: 0, err_desc: null });
})
});
Angular controller
.module('CIController', ['ngMaterial', 'ngAnimate', 'ngAria', 'ngMessages', 'Alertify', 'ngFileUpload',])
.controller('childController', ['$scope', '$location', '$q', '$timeout', '$log', 'CIFactory', 'ClientConfig', 'Alertify', 'Upload', '$window', function ($scope, $location, $q, $timeout, $log, CIFactory, ClientConfig, Alertify, Upload, $window) {
.....
$scope.submitfile = function () { //function to call on form submit
if ($scope.indexForm.$valid && $scope.BuildModel.file) { //check if from is valid
var isuploaded = $scope.uploadfiletoserver($scope.BuildModel.file); //call upload function
}
}
$scope.uploadfiletoserver = function (file) {
Upload.upload({
url: '/upload', //webAPI exposed to upload the file
data: { file: file } //pass file as data, should be user ng-model
}).then(function (resp) { //upload function returns a promise
if (resp.data.error_code === 0) { //validate success
console.log("inside upload controller");
$window.alert('Success ' + resp.config.data.file.name + 'uploaded. Response: ');
return ClientConfig.BOOL_TRUE;
} else {
$window.alert('an error occured');
return ClientConfig.BOOL_FALSE;
}
}, function (resp) { //catch error
console.log('Error status: ' + resp.status);
$window.alert('Error status: ' + resp.status);
return ClientConfig.BOOL_FALSE;
}, function (evt) {
console.log(evt);
var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
console.log('progress: ' + progressPercentage + '% ' + evt.config.data.file.name);
$scope.progress = 'progress: ' + progressPercentage + '% '; // capture upload progress
});
};
In HTML
<form name="indexForm" invalidfieldfocus novalidate id="indexForm" autocomplete="off" enctype="multipart/form-data">
<div>
<input type="file" ngf-select ng-model="$parent.BuildModel.file" name="file" ngf-max-size="20MB" />
<i ng-show="indexForm.file.$error.required">*required</i><br>
<i ng-show="indexForm.file.$error.maxSize">File too large {{indexForm.file.size / 1000000|number:1}}MB: max 20M
</i>
<p>{{indexForm.file.progress}}
</div>
Now there is no error.
Make sure ng-file-upload all JavaScript files are included in HTML.
Include the ngFileUpload in controller as I have given above in the code part.
Install ng-multer and write the required funtion as shown above and the path we mention should have the folder already created otherwise it throws error.
I am trying to upload my files with ng file upload but they are uploaded with some different file name on the server.I want them to get saved with the file name they have originally with their correct extension(.jpg,.pdf).
Below is my code.
Controller:
$scope.uploadPic = function (file) {
$scope.advert.userDetails={
"name":userDetails.name,
"email":userDetails.email,
"role":userDetails.role
}
file.upload = Upload.upload({
url: '/api/uploaders/uploads',
method: 'POST',
fields: {
details: $scope.advert
},
file: file,
fileFormDataName: 'photo'
});
file.upload.then(function (response) {
console.log("Postcontroller: upload then ");
$timeout(function () {
file.result = response.data;
});
}, function (response) {
if (response.status > 0)
$scope.errorMsg = response.status + ': ' + response.data;
});
file.upload.progress(function (evt) {
// Math.min is to fix IE which reports 200% sometimes
file.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
console.log("PostController: upload progress " + file.progress);
});
file.upload.success(function (data, status, headers, config) {
// file is uploaded successfully
console.log('file ' + config.file.name + 'is uploaded successfully. Response: ' + data);
console.log(data);
});
}
Api:
var multer = require('multer');
var upload = multer({ dest: 'server/uploads/images'});
It's not ng-upload changing the filename, it's multer. This is for security reasons.
In a nutshell, you wouldn't want someone to know the exact path of a file they've uploaded - what if it were malicious? They could potentially execute it.
If you really want, however, you can do this on your API side:
var multer = require('multer');
var storage = multer.diskStorage(
{
destination: 'server/uploads/images',
filename: function (req, file, cb) {
cb(null, file.originalname);
}
}
);
var upload = multer(storage);
I am trying to upload files using Node Api on server and i m using ngfileupload angular Module to handle image on front end.
below is my code:
app.controller('MyCtrl',['Upload','$window',function(Upload,$window){
var vm = this;
vm.submit = function(){
if (vm.upload_form.file.$valid && vm.file) {
vm.upload(vm.file);
}
}
vm.upload = function (file) {
Upload.upload({
url: '/api/upload',
data:{file:file} model
}).then(function (resp) {
if(resp.data.error_code === 0){ //validate success
$window.alert('Success ' + resp.config.data.file.name + 'uploaded. Response: ');
} else {
$window.alert('an error occured');
}
}, function (resp) {
console.log('Error status: ' + resp.status);
$window.alert('Error status: ' + resp.status);
}, function (evt) {
console.log(evt);
var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
vm.progress = 'progress: ' + progressPercentage + '% ';
});
};
}]);
and my node api code is
apiRoutes.put('/upload', function(req, res){
var fstream;
req.pipe(req.busboy);
req.busboy.on('file', function(fieldname,file,filename){
var filePath=path.join(__dirname, './public/file', filename);
fstream=fs.createWriteStream(filePath);
file.pipe(fstream);
fstream.on('close', function(){
console.log("File Saved...........");
});
});
});
Now problem is that , when i hit upload button its showing an alert Error Status:404 and an error:
Not allowed to load local resource: file:///C:/fakepath/IMG-20160126-WA0013.jpg
I dont know how to fix it...
please help me
NgFileUpload send POST request by default. Your api router accepts PUT requests only.
Try to change apiRoutes.put... to apiRouter.post... or set
Upload.upload({
url: '/api/upload',
data: {file:file},
method: 'PUT'
})
I am using this ng-file-upload module and i used ngf-pattern to restrict image file type those only allowable to upload. In case someone upload wrong file type, then, I need to display a box that should show error box to user Invalid file type has been uploaded.
On my below code, for example, I have used supported images file type jpg on ngf-pattern. I should display error in case I upload png file
On the same, I want to display the error on wrong file type is uploaded.
Please help me on this.
HTML CODE
<div ng-controller="AssetsUploadController">
<div class="assetsUploadSection">
<div ngf-drop="uploadFiles($files, $invalidFiles)" class="assets-drop-box" ngf-drag-over-class="assets-dragover" ngf-multiple="true" ngf-pattern="'image/jpg,image/jpeg,videos/*,application/pdf'"><img src="dragDrop.png"/>
<button ngf-select="uploadFiles($files, $invalidFiles)" multiple type="button">Upload Assets</button></div></div>
</div>
Angular code
var app = angular.module('myApp', ['ngFileUpload']);
app.controller('ImageController', function ($scope, Upload,$timeout) {
$scope.upload = function (file) {
Upload.upload({
url: 'upload/url',
data: {file: file, 'username': $scope.username}
}).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);
});
};
$scope.uploadFiles = function (files) {
$scope.files = files;
console.log('upload files'+ files);
if (files && files.length) {
Upload.upload({
url: 'https://angular-file-upload-cors-srv.appspot.com/upload',
data: {
files: files
}
}).then(function (response) {
$timeout(function () {
$scope.result = response.data;
});
}, function (response) {
if (response.status > 0) {
$scope.errorMsg = response.status + ': ' + response.data;
}
}, function (evt) {
$scope.progress =
Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
});
}
}
});
I am a newbie to angularjs and I want to create a form with a file. How can I get the file on angularjs controller and pass it to the laravel?
Take a look to the ng-file-upload is very easy to configure and use and there are some examples for the server side code (also PHP).
If you are using bower, install runnig:
bower install ng-file-upload --save
and add the ngFileUpload to your module:
var app = angular.module('myApp', [
// other dependencies here
'ngFileUpload'
]);
HTML:
<div class="button" ngf-select ngf-change="upload($files)">Upload on file change</div>
Controller:
$scope.upload = function (files) {
if (files && files.length) {
for (var i = 0; i < files.length; i++) {
var file = files[i];
Upload.upload({
url: 'upload/url', // change this with the url/route of your laravel action
fields: {'username': $scope.username}, // this is an example to pass additional fields to pass in the post
file: file
}).progress(function (evt) {
var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
console.log('progress: ' + progressPercentage + '% ' + evt.config.file.name);
}).success(function (data, status, headers, config) {
console.log('file ' + config.file.name + 'uploaded. Response: ' + data);
alert('file uploaded!');
});
}
}
};
See the demo fiddle