1

我正在尝试使用 Angular 上传一个文件,并且我得到了 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");
        }
    }
4

1 回答 1

0

而不是发送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 类型并发送二进制数据。

于 2016-12-05T06:07:15.027 回答