Angularjs and laravel file upload on form submission - angularjs

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

Related

HOw to save file with original file name with ng file upload on the server

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);

files are not storing in local using ngfileupload

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'
})

How to add function for wrong file type[image] upload in ng-file-upload

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));
});
}
}
});

file upload in sails

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.

File upload using Angular js and grails

I am trying to implement a file upload using angular js and grails. I am able to call the grails controller method but not able to get the file from angular js using request.getFile() method. Here is my html code,
<script src="angular-file-upload-shim.min.js"></script>
<script src="angular.min.js"></script>
<script src="angular-file-upload.min.js"></script>
<div ng-controller="MyCtrl">
<input type="text" ng-model="myModelObj">
<input type="file" name="file" ng-file-select="onFileSelect($files)" >
<div ng-file-drop="onFileSelect($files)" ng-file-drag-over-class="optional-css-class"
ng-show="dropSupported">drop files here</div>
<div ng-file-drop-available="dropSupported=true"
ng-show="!dropSupported">HTML5 Drop File is not supported!</div>
<button ng-click="upload.abort()">Cancel Upload</button>
</div>
Here is the javascript code,
//inject angular file upload directives and service.
angular.module('myApp', ['angularFileUpload']);
var MyCtrl = [ '$scope', '$upload', function($scope, $upload) {
$scope.onFileSelect = function($files) {
//$files: an array of files selected, each file has name, size, and type.
for (var i = 0; i < $files.length; i++) {
var file = $files[i];
$scope.upload = $upload.upload({
url: 'GrailsApp/upload', //upload.php script, node.js route, or servlet url
data: {myObj: $scope.myModelObj},
file: file, // or list of files: $files for html5 only
}).progress(function(evt) {
console.log('percent: ' + parseInt(100.0 * evt.loaded / evt.total));
}).success(function(data, status, headers, config) {
// file is uploaded successfully
console.log(data);
});
}
};
}];
Here is the grails controller upload method,
def upload() {
def f = request.getFile('file')
if (f.empty) {
flash.message = 'file cannot be empty'
render(view: 'uploadForm')
return
}
f.transferTo(new File('D:/Filestorage/myfile.txt')) response.sendError(200, 'Done') }
While running this code gives a error like below,
Request.getFile() is applicable for argument types: (java.lang.String) values: {"file"}
But definitely it is going inside the controller method. Just not able to get the file from angular js.
But the same code works when I use a gsp form like below,
<g:uploadForm action="upload">
<input type="file" name="file" />
<input type="submit" />
</g:uploadForm>
The same code works like a chram and upload the file successfully.
Docs say the fileName by default is file but add fileFormDataName: "myFile" explicitly as:
$scope.upload = $upload.upload({
url: 'GrailsApp/upload', //upload.php script, node.js route, or servlet url
data: {myObj: $scope.myModelObj},
file: file,
fileFormDataName: "myFile"
}).progress(function(evt) {
console.log('percent: ' + parseInt(100.0 * evt.loaded / evt.total));
}).success(function(data, status, headers, config) {
// file is uploaded successfully
console.log(data);
});
in angular and then get the file as
request.getFile('myFile')
in Grails side to see if it works.
Also see, instead of explicitly adding a fileFormDataName just rectify that you have removed the trailing , from file: file, and use as earlier, if that helps.
The issue has been fixed. Just need to bind the post with a name, by adding fileFormDataName:"file" in the $scope.upload method.
Here is a sample,
//inject angular file upload directives and service.
angular.module('myApp', ['angularFileUpload']);
var MyCtrl = [ '$scope', '$upload', function($scope, $upload) {
$scope.onFileSelect = function($files) {
//$files: an array of files selected, each file has name, size, and type.
for (var i = 0; i < $files.length; i++) {
var file = $files[i];
$scope.upload = $upload.upload({
url: 'GrailsApp/upload', //upload.php script, node.js route, or servlet url
data: {myObj: $scope.myModelObj},
file: file,
fileFormDataName:'file'
}).progress(function(evt) {
console.log('percent: ' + parseInt(100.0 * evt.loaded / evt.total));
}).success(function(data, status, headers, config) {
// file is uploaded successfully
console.log(data);
});
}
};
}];

Resources