Home > Enterprise >  How to upload a file from frontend using query string
How to upload a file from frontend using query string

Time:09-16

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.

CodePudding user response:

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?

CodePudding user response:

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

  • Related