Quick Expense Manger. Your free expense manager. Lots of features. The application is also ad free.

Send Image in Form Data in Angular

Posted on Nov. 11, 2017
send-image-in-form-data-angular

I struggled a lot while trying to send an image in form data in angular js to REST end point. I hope this article will help you to successfully send an image in form data.


In this article we will take an example of sending an image of a student along with a student registration form. We assume that we have a controller named adminController defined in our Angular JS. We can create a display to upload student photo as below.

<div class="form-group">
<img src="{{adminController.studentPhoto}}" class ="img-responsive img-center"
alt="">
<div class="input-group" style="margin-top:10px">
<span class="input-group-btn">
<span class="btn btn-default btn-file">
Upload photo… <input type="file" id="imgInp" name="file" fileread=
"adminController.studentPhoto">
</span>
</span>
<input type="text" name="text" value="{{adminController.textOfPhoto}}"
class="form-control text-center" readonly>

</div>
</div>

The fileread is a custom directive that we can write as below in our angular app.


app.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]);
});
}
}
}
]);

We can use the below code to send our image along with the Form data to our REST end point.


self.updateStudentInfo = function(){

var fd = new FormData();

var imgBlob = dataURItoBlob(self.studentPhoto);
fd.append('photo', imgBlob);

var studentObject = self.getStudentObject();
fd.append('student', JSON.stringify(studentObject));

$http.post('http://localhost:port/students/update-student',fd,{
headers: {'Content-Type': undefined},
transformRequest: angular.identity,

}).success(function(data) {
alert("student update success");
}).error(function() {
alert("student update failed");
});
}

Here are the functions dataURItoBlob() and getStudentObject(). The important thing to note is 'Content-Type': undefined and transformRequest: angular.identity


function dataURItoBlob(dataURI) {

// convert base64/URLEncoded data component to raw binary data held in a string
var byteString;
if (dataURI.split(',')[0].indexOf('base64') >= 0)
byteString = atob(dataURI.split(',')[1]);
else
byteString = unescape(dataURI.split(',')[1]);

// separate out the mime component
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];

// write the bytes of the string to a typed array
var ia = new Uint8Array(byteString.length);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}

return new Blob([ia], {type:mimeString});

}
self.getStudentObject = function(){
var object = new Object();

object.id = self.idStudent;
object.name = self.firstName;
object.email = self.email;
object.phoneNumber = self.phone;

return object;
}

I hope this would help you to successfully send image along with form data.

Sharing is Caring!

Quick Expense Manger. Your free expense manager. Lots of features. The application is also ad free.

GET FREE UPDATES


RECOMMENDED POSTS FOR YOU


profile image

Kaushik Baruah


ABOUT

My name is Kaushik Baruah and I am the chief blogger on this Blog and here I like to share my experience as software engineer and research engineer with my online readers. I will try to focus on career planning, latest emerging technologies and tutorials on various computer science subjects. You can follow me on Twitter, Facebook and Google+

GET FREE UPDATES

POPULAR POSTS

Copyright © 2016
About Us

My name is Kaushik Baruah and I am the chief blogger on this Blog and here I like to share my experience as software engineer and research engineer with my online readers. I will try to focus on career planning, latest emerging technologies and tutorials on various computer science subjects.

Get Free Updates