How to send Data and Image with formdata

Posted By : Mayank Tyagi | 01-May-2015
How to send data with forn data in in angularjs

 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

 

About Author

Author Image
Mayank Tyagi

Mayank is a bright Web Developer with expertise in Java language.

Request for Proposal

Name is required

Comment is required

Sending message..