Angular upload - error 405 When Sending FormData [duplicate]

落爺英雄遲暮 提交于 2019-12-02 08:54:58

问题


I am trying to upload a file with angular and I am getting post result 405. After researching in internet I found out that this is a response when the method is not allowed. I can not figure out why I am getting this error. Thanks in advance for the help.

HTML

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

Directive

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]);
            });
        });
    }
};
}]);

Service

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);
    });
}
}]);

Controller

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 });
};

}]);

Backend

[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");
        }
    }

回答1:


Instead of sending FormData, send the file directly:

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 }
    })
}
}]);

When the browser sends FormData, it uses 'Content-Type': multipart/formdata and encodes each part using base64.

When the browser sends a file or blob, it sets the content type to the MIME-type of the file or the blob and sends binary data.



来源:https://stackoverflow.com/questions/40959286/angular-upload-error-405-when-sending-formdata

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