-1

I have one form with some fields in AngularJs. I want to add one more field in form to upload a file, Currently I am sending data to backend as json payload, how can I upload a file that's my question, I have one idea that is by using query string... Anyone can please let me know how can I do this thing. My code to upload text fields -

    let settings = {
      "url": "https://someurl",
      "method": "POST",
      "timeout": 0,
      "headers": {
        "Content-Type": "application/json",
      },
      "data": JSON.stringify(data)
    };
    
    $.ajax(settings).done(function (response) {
        toastr["success"]("Form submitted succesfully.", "Success!");
        setTimeout(function () {
          window.location.href = "success.php";
        }, 1500);
      }).fail(function (err) {
          toastr["error"]("Cannot submit your form.", "Failed!");
      }
   };

I am using AngularJs for the frontend.

2 Answers 2

1

Two ways:

1 - Use Json: You can convert file to base64 and push to server like simple JSON Image convert to Base64

2 - Use FormData: change content type to: 'multipart/form-data' and use formData in body like this How to use FormData for AJAX file upload?

Sign up to request clarification or add additional context in comments.

Comments

1

Try this :

 <form name="myForm" ng-submit="_post(file,data)">
     <input ng-model='file' type="file"/>
     <input ng-model='data.name' type="text"/>
     <input ng-model='data.age' type="number"/>
     <input type="submit" value='Submit'/>
 </form>


 var _post = function (file, jsonData) {
        $http({
            url: your url,
            method: "POST",
            headers: { 'Content-Type': undefined },
            transformRequest: function (data) {
                var formData = new FormData();
                formData.append("model", angular.toJson(data.model));
                formData.append("file", data.files);
                return formData;
            },
            data: { model: jsonData, files: file }
        }).then(function (response) {
            ;
        });

Working fiddle

4 Comments

Any explainations?
what is the use of "formData.append("model", angular.toJson(data.model));" this line ?
@Amara. This is used to send data to your server in form data format. This is how files are sent to server usually.
@Amara. I've added a working fiddle for you. jsfiddle.net/2jLnv1qa

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.