How to send Data and Image with formdata
Posted By : Mayank Tyagi | 01-May-2015
In order to send data with image's formdata you need to create a JSON in your enquiry controller and bind the JSON data with that formdata .To understand this this let's go through wit an example:-
//creating JSON according to your view fields
$scope.reqData = {
comment: "",//according to your fields in html binded with model
isRevision: ""
};
//then create a form data and append the image and data with them when sendEnquiry() method is called
//callling the method of the server where the image and JSON is to be send
$scope.sendEnquiry = function () {
this.spinner = true;
var formDataForAttachmentEnquiry = new FormData();//creating a form data
formDataForAttachmentEnquiry.append("file", document.getElementById("attachment").files[0]);//you need to define the id of image in html
formDataForAttachmentEnquiry.append("data", JSON.stringify(this.reqData));//appending the data in form
//use http.post or your service method to send the data
enquiryService.sendEnquiry(requirementId, formDataForAttachmentEnquiry).success(function (response) {
this.allEnquiries.push(response.response);
this.reqData.comment = "";
this.spinner = false;
});
};
//enquiryService.sendEnquiry() is maintained in the service of the controller
var sendEnquiry = function (requirementId, formDataForAttachmentEnquiry) {
var sendEnquiry = $http.post("/api/v1/user/requirement/" + requirementId + "/enquiry", formDataForAttachmentEnquiry, {
withCredentials: true,
headers: {
'Content-Type': undefined
},
transformRequest: angular.identity
});
return sendEnquiry;
}
Now after sending the data from the client side you need to pull the data from the request,so in order to get the data you need to de
request.body.data //to get your JSON data appended with the form data
and
request.files.file //to get the image sended via form
I hope you found this blog helpful.
THANKS
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Mayank Tyagi
Mayank is a bright Web Developer with expertise in Java language.