Angular 上传 - 发送 FormData 时出现错误 405

Angular upload - error 405 When Sending FormData

我正在尝试使用 angular 上传一个文件,我得到 post 结果 405。在互联网上进行研究后,我发现这是在不允许该方法时的响应。我不知道为什么会收到此错误。 在此先感谢您的帮助。

HTML

<input type="file" file-model="myFile" />
<button ng-click="uploadFile()">upload me</button>

指令

MyApp.directive('fileModel', ['$parse', function ($parse) {
return {
    restrict: 'A',
    link: function (scope, element, attrs) {
        var model = $parse(attrs.fileModel);
        var modelSetter = model.assign;

        element.bind('change', function () {
            scope.$apply(function () {
                modelSetter(scope, element[0].files[0]);
            });
        });
    }
};
}]);

服务

MyApp.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function (file, uploadUrl) {
    var fd = new FormData();
    fd.append('file', file);
    $http.post(uploadUrl, fd, {
        transformRequest: angular.identity,
        headers: { 'Content-Type': undefined }
    })
    .then(function (response) {
        console.log(1);
    })
    .catch(function (error) {
        console.log(2);
    });
}
}]);

控制器

MyApp.controller('AdminController', ['$scope', '$http', '$location', 'fileUpload', function ($scope, $http, $location, fileUpload) {
var baseUrl = $location.protocol() + "://" + location.host + "/";
$scope.uploadFile = function () {
    var file = $scope.myFile;
    $http.post(baseUrl + "Admin/uploadFile", { data: file });
};

}]);

后端

[HttpPost]
    public ActionResult uploadFile(dynamic data)
    {
        try
        {
            MultiModel mcqModel = new MultiModel();
            mcqModel.editAddQuestionAnswers(data);
            Response.StatusCode = 200;
            return Content("updated");
        }
        catch (Exception ex)
        {
            Response.StatusCode = 500;
            return Content("Fail");
        }
    }

不发送FormData,而是直接发送文件:

MyApp.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function (file, uploadUrl) {
    //var fd = new FormData();
    //fd.append('file', file);
    //$http.post(uploadUrl, fd, {
    $http.post(uploadUrl, file, {
        transformRequest: angular.identity,
        headers: { 'Content-Type': undefined }
    })
}
}]);

当浏览器发送FormData时,它使用'Content-Type': multipart/formdata并使用base64对每个部分进行编码。

当浏览器发送文件或 blob 时,它会将内容类型设置为文件或 blob 的 MIME 类型并发送二进制数据。