1

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"); } } 
3
  • 1
    post your backend code ... this is not a front end issue
    – Sherif
    CommentedDec 4, 2016 at 13:55
  • What method is required by the API? Do you understand the 405 error?
    – Tim Grant
    CommentedDec 4, 2016 at 13:56
  • Thank you. I added my back end code as well. Do I need to stringify or do anything else with the file before I send it to the back end. I will upload videos and most likely their size will be around 100 mb. Am I using the right approach?
    – user7199461
    CommentedDec 4, 2016 at 14:19

1 Answer 1

0

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.