File Upload using AngularJS

前端 未结 29 1994
野趣味
野趣味 2020-11-21 07:24

Here is my HTML form:

29条回答
  •  迷失自我
    2020-11-21 07:59

    Your file and json data uploading at the same time .

    // FIRST SOLUTION
     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) {
                    ;
                });
            }
    // END OF FIRST SOLUTION
    
    // SECOND SOLUTION
    // If you can add plural file and  If above code give an error.
    // You can try following code
     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));
                    for (var i = 0; i < data.files.length; i++) {
                        // add each file to
                        // the form data and iteratively name them
                        formData.append("file" + i, data.files[i]);
                    }
                        return formData;
                    },
                    data: { model: jsonData, files: file }
                }).then(function (response) {
                    ;
                });
            }
    // END OF SECOND SOLUTION

提交回复
热议问题