问题
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