How do I upload a multipart form in AngularJS?

一个人想着一个人 提交于 2019-12-05 21:43:34

use this module https://github.com/danialfarid/angular-file-upload is very simple to use.

ex:

    var $file;//single file 
    $scope.sendFiles= function(){
     $upload.upload({
                        url: yourUrl,
                        method: "POST",
                        data: { data: $scope.yourOtherObject },
                        file: $file
                    }).success(function (data, status, headers, config) {
                        // file is uploaded successfully
                        console.log(data);
                        console.log("File upload SUCCESS");
                    }).error(function (data, status) {
                       console.log("File upload FAILED");
                    });
    } 

    $scope.onFileSelect = function ($files) {
                for (var i = 0; i < $files.length; i++) {
                    $file = $files[i];//set a single file
                }
           };

HTML CODE

<input type="file" name="myfile" ng-file-select="onFileSelect($files)" />
<button ng-click='sendFiles()'>Send file</button>

The problem is the $http service, by default use content-type as application/json and in your case it must be application/x-www-form-urlencoded To solve this you can use the following directive: https://github.com/nervgh/angular-file-upload/wiki/Module-API, it also has support for send data along with the files.

Another aproach is to use the formData object along with XmlHttpRequest in your directive, like this:

                var data = new FormData();
                var xhr = new XMLHttpRequest();
                data.append('file', files[i], files[i].name);
                xhr.open('POST', scope.mseUploadFile);
                xhr.onreadystatechange = function () {
                    if (xhr.readyState == 4 && xhr.status == 200) {
                        var result = xhr.responseText;

                        if (scope.callback) {
                            scope.$apply(function () {
                                scope.callback({ $data: result });
                            });
                        }

                    }
                    else if (xhr.readyState == 4 && xhr.status == 400) {
                        scope.$apply(function () {
                            if (scope.onError) {
                                scope.onError({ $error: xhr.responseText });
                            }
                            handleError(xhr.responseText);
                        });

                    }
                };
                xhr.send(data);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!