Upload angular multi-part - javascript

I made this example: http://jsfiddle.net/ejx68/6/ to upload multi-part file but there are two things i can't do.
1) Upload more than one file. So use the multiple condition on input
2) append other formData() that i have in the controller to the service.
Here the example:
var myApp = angular.module('myApp', []);
myApp.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]);
});
});
}
};
}]);
myApp.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file, uploadUrl, callback){
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(callback)
.error(callback);
}
}]);
myApp.controller('myCtrl', ['$scope', 'fileUpload', function($scope, fileUpload){
$scope.uploadFile = function(){
var file = $scope.myFile;
console.log('file is ' + JSON.stringify(file));
console.log(fileUpload.fd);
fileUpload.fd.append('newID', "2");
var uploadUrl = "http://httpbin.org/post";
fileUpload.uploadFileToUrl(file, uploadUrl,function(data, status, headers, config){
if(status == 200)console.log('Success!');
else console.log('Error!');
});
};
}]);
<div ng-controller = "myCtrl">
<input type="file" file-model="myFile"/>
<button ng-click="uploadFile()">upload me</button>
</div>
thanks

Related

How to change the name of the image?

Angularjs
app.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]);
});
});
}
};
}]);
app.service('fileUpload', ['$http', function ($http) {
this.uploadFileAndFieldsToUrl = function(file, fields, uploadUrl){
var fd = new FormData();
fd.append('file', file);
console.log(file) //File { name: "franklindroosevelt1.jpg", lastModified: 1522139208000, lastModifiedDate: Date 2018-03-27T08:26:48.000Z, webkitRelativePath: "", size: 63159, type: "image/jpeg" }
for(var i = 0; i < fields.length; i++){
fd.append(fields[i].name, fields[i].data)
}
console.log(file)//File { name: "franklindroosevelt1.jpg", lastModified: 1522139208000, lastModifiedDate: Date 2018-03-27T08:26:48.000Z, webkitRelativePath: "", size: 63159, type: "image/jpeg" }
$http.post(Appname+"/upload_image/", fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
})
.error(function(){
});
}
}]);
app.controller('myCtrl', ['$scope', 'fileUpload', function($scope, fileUpload){
$scope.$watch('myFile', function(newFileObj){
if(newFileObj)
$scope.filename = newFileObj.name;
});
$scope.uploadForm = function(){
var file = $scope.myFile;
var uploadUrl = "/formUpload";
var fields = [{"name": "filename", "data": $scope.filename}];
fileUpload.uploadFileAndFieldsToUrl(file, fields, uploadUrl);
};
}]);
HTML
<div class="maincontent">
<div ng-app="Appschedule" ng-controller="myCtrl" class="container container1">
<p>
<input type="file" file-model="myFile"/>
</p>
<p>
<label>File Name:</label>
<input type="text" ng-model="filename"></input>
</p>
<button ng-click="uploadForm()">upload me</button>
</div>
</div>
I had written a code to upload a image into directory , here i want to change the image name based on input text or any random name.I cant change the name , the name remains same while uploading. Is there any other way to send the name. please help me
Is there any other way to send the name?
Here is code showing how to send name as string and file in the same request:
myApp.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file, uploadUrl){
var fd = new FormData();
fd.append('file', file);
var info = {
"text":"file_name"
};
fd.append('data', angular.toJson(info));
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
})
.error(function(){
});
}
}]);
On server side it's in req.body.data, so it can be received i.e. like this:
upload(req, res, function (err) {
if (err) {
res.json({error_code: 1, err_desc: err});
return;
}
console.log(req.body.data);
res.json({error_code: 0, err_desc: null});
})

How to post a json data and a file using angular js formdata

I tried sending json data and a single file using angular formdata but its not working. I don't receive json from my server. Here is my code with angularjs
angular
.module('app')
.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]);
});
});
}
};
}]);
angular
.module('BossApp')
.controller('addresumeCtrl', addresumeCtrl);
function addresumeCtrl ($scope,ngDialog,$http) {
$scope.resume = {};
$scope.resume.educations = [];
$scope.resume.experiences = [];
$scope.create = function(){
var uploadUrl = "/user/add-resume";
var fd = new FormData();
for(var key in $scope.resume)
fd.append(key, $scope.resume[key]);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
}).then(function (response) {
}, function (error) {
});
};
}
How to fix this?

Angular upload onchange event :getting empty file in server

Here is my code to upload file to server on input change
$scope.uploadImage = function (f) {
$http.post('/art',{'image':f},{headers: {'Content-Type': undefined}}).then(function (response) {
console.log(response);
});
}
but i will get empty files in server however i check my serverside code with normal fileupload it works fine without any problem
Serverside
//get empty in angular upload
console.log(req.file('image'));
req.file('image').upload({
// don't allow the total upload size to exceed ~10MB
maxBytes: 10000000
},function whenDone(err, uploadedFiles) {
return res.json({
'status':uploadedFiles
})
});
HTML
<input type="file" ng-model="art.artImage" onchange="angular.element(this).scope().uploadImage(this.files)" name="artImage" id="artImage">
I believe its problem with content-type in angular http post request
when the input type is file file will not attach the model. You need a workaround like this.
.directive("fileread", [function () {
return {
scope: {
fileread: "="
},
link: function (scope, element, attributes) {
element.bind("change", function (changeEvent) {
var reader = new FileReader();
reader.onload = function (loadEvent) {
scope.$apply(function () {
scope.fileread = loadEvent.target.result;
});
}
reader.readAsDataURL(changeEvent.target.files[0]);
});
}
}
}]);
change the input like
<input type="file" fileread="art.artImage" onchange="angular.element(this).scope().uploadImage(this.files)"
name="artImage" id="artImage">
use the multipart header in your request
$http.post('/art', {
'image': art.artImage
}, {
transformRequest: angular.identity,
headers: {
'Content-Type': "multipart/form-data"
}
})
Use ng-fileUpload lib for angularjs
My HTML
<form method="post" enctype="multipart/form-data" ng-controller="commentCtrl" name="form">
<img src="source/assets/images/icons/icofileattached.png" class="attachmentpng-height" ngf-select="uploadFiles($file)" ng-model="files"/>
<md-button type="submit" class="md-raised custom-submit-button" ng-click="MakeComments()"> SUBMIT </md-button>
</form>
My Controller code
$scope.uploadFiles = function(file) {
console.log(file);
$scope.fileData = file;
var fd = new FormData();
fd.append('file', file);
Restangular.one('/api/files/end points').withHttpConfig({transformRequest: angular.identity})
.customPOST(fd, '', undefined, {'Content-Type': undefined})
};
Please try this , avoid using onload in HTML tag for file :
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
</head>
<body ng-app = "myApp">
<div ng-controller = "myCtrl">
<input type = "file" file-model = "myFile"/>
<button ng-click = "uploadFile()">upload me</button>
</div>
<script>
var myApp = angular.module('myApp', []);
myApp.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]);
});
});
}
};
}]);
myApp.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file, uploadUrl){
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
alert("Done");
})
.error(function(){
alert("Sorry");
});
}
}]);
myApp.controller('myCtrl', ['$scope', 'fileUpload', function($scope, fileUpload){
$scope.uploadFile = function(){
var file = $scope.myFile;
console.log('file is ' );
console.dir(file);
var uploadUrl = "/art";
fileUpload.uploadFileToUrl(file, uploadUrl);
};
}]);
</script>
</body>
</html>

how to save/upload image in local/project folder using angular js?

I am tryout on save in local project folder using angular and i have not correct code anyone put it your solution help me lot more and then my code here as
this.uploadFileToUrl = function(file, uploadUrl){
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
})
.error(function(){
});
}
This is an example code to upload files. You can try it out using this example.
<html>
<head>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>
<body ng-app = "myApp">
<div ng-controller = "myCtrl">
<input type = "file" file-model = "myFile"/>
<button ng-click = "uploadFile()">upload me</button>
</div>
<script>
var myApp = angular.module('myApp', []);
myApp.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]);
});
});
}
};
}]);
myApp.service('fileUpload', ['$https:', function ($https:) {
this.uploadFileToUrl = function(file, uploadUrl){
var fd = new FormData();
fd.append('file', file);
$https:.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
})
.error(function(){
});
}
}]);
myApp.controller('myCtrl', ['$scope', 'fileUpload', function($scope, fileUpload){
$scope.uploadFile = function(){
var file = $scope.myFile;
console.log('file is ' );
console.dir(file);
var uploadUrl = "/fileUpload";
fileUpload.uploadFileToUrl(file, uploadUrl);
};
}]);
</script>
Hey Kalithas KN and welcome to StackOverflow.
For file upload, I have found the following Angular JS library works the best for me
https://github.com/danialfarid/ng-file-upload
The upload method will look something like this
$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);
});
};
In your template, you would do something like this
<div class="button" ngf-select="upload($file)">Upload on file select</div>
Also, the library can handle drag and drop file upload which i think is always a nice addition.
I hope this helps. Please let me know if you need more clarifications.

Input type file is not clearing up when successfully submitting the form

When i am submitting the form the input text is clearing up but the uploaded file is not clearing. I have used $scope.addAnswerForm.$setPristine(); but this is not working.
app.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]);
});
});
}
};
}
]);
app.controller("MyCtrl", function($scope, $http) {
$scope._answer = {
text: '',
comment_pic: ''
};
$scope.__answer = JSON.parse(JSON.stringify($scope._answer));
$scope.addAnswer = function(todo) {
var data = {
answer: $scope.__answer.text,
comment_pic: $scope.__answer.comment_pic,
};
var fd = new FormData();
for (var key in data) {
fd.append(key, data[key])
};
$http({
url: '/posturl'
data: fd,
method: "POST",
headers: {
'Content-Type': undefined
}
}).success(function(data, status) {
todo.answers.push($scope.__answer);
$scope._answer.comment_pic = "";
$scope.__answer = JSON.parse(JSON.stringify($scope._answer));
});
};
});
<div ng-controller="myCtrl">
<form name="addAnswerForm">
<input ng-model="__answer.text" />
<input type="file" file-model="__answer.comment_pic" />
<button type="submit" ng-click="addAnswer(discussion)">Post</button>
</form>
</div>
how to make the form clear after submitting the form
This the file in the input type="file" is not getting cleared
By clearing the DOM of the form the form is getting cleared.
document.getElementById("MyformId").reset();
if there is another method do tell

Categories

Resources