将文件从AngularJs上传到C#Web API作为正文

时间:2017-04-28 12:24:30

标签: c# angularjs asp.net-web-api2 ng-file-upload steam-web-api

我有一个Angular应用程序,因为我浏览了一个文件(例如:一个XML文件),并且我发送了一些信息,例如'Username':'bala'



<html>
   
   <head>
      <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
   </head>
   
   <body ng-app = "myApp">
	
      <div ng-controller = "myCtrl">
         <input type = "file" file-model = "myFile"/>
         <button ng-click = "uploadFile()">upload me</button>
      </div>
      
      <script>
         var myApp = angular.module('myApp', []);
         
         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,}
            })

            .success(function(){
            })

            .error(function(){
            });
        },
        this.uploadFileToUrlasBody = function(file, uploadUrl){
            var fd = new FormData();
            fd.append('file', file);

            $http({
            method: 'POST',
            url: uploadUrl,
            headers: {
                'Content-Type': 'multipart/form-data'
            },
            data: {
                username:'ram',
                file: file
            },
            transformRequest: function (data, headersGetter) {
                var formData = new FormData();
                angular.forEach(data, function (value, key) {
                    formData.append(key, value);
                });

                var headers = headersGetter();
                delete headers['Content-Type'];

                return formData;
            }
        })

            .success(function(){
            })

            .error(function(){
            });
        }
        }]);
      
         myApp.controller('myCtrl', ['$scope', 'fileUpload', function($scope, fileUpload){
            $scope.uploadFile = function(){
               var file = $scope.myFile;
               
               console.log('file is ' );
               console.dir(file);
               
               var uploadUrl = "http://localhost:40005//api/Sample/UploadData";
               fileUpload.uploadFileToUrlasBody(file, uploadUrl);
            };

$scope.str2ab = function (data) {
    var json = JSON.stringify(data);
    console.log(json);
            var blob = new Blob(data);
    return blob;
    }

         }]);
			
      </script>
      
   </body>
</html>
&#13;
&#13;
&#13;

我的C#Web API具有带以下签名的Controller方法

[HttpPost]
public void UploadData(SomeModel model) {
    // Main Logic
}

public class SomeModel {
    public string username { get; set; }
    public dynamic file { get; set; } //<-- Wonder if this is right way ?
}

HTTP Post Request未达到此控制器方法。

我收到了以下请求标题

Host: localhost:40005
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:53.0) Gecko/20100101 Firefox/53.0
Accept: application/json, text/plain, */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Content-Length: 381
Content-Type: multipart/form-data; boundary=---------------------------117853232617487
Origin: null
Connection: keep-alive

请求正文:

-----------------------------117853232617487
Content-Disposition: form-data; name="username"

ram
-----------------------------117853232617487
Content-Disposition: form-data; name="file"; filename="Client.xml"
Content-Type: text/xml

<?xml version="1.0" encoding="utf-8"?><Root><TimeOut>00:15:00</TimeOut></Root>
-----------------------------117853232617487--

最后它返回HTTP状态码415 Unsupported Media Type

请帮助我如何将Body中的文件作为对象发送(可能是字节数组或流)

  

注意:不要将文件作为字符串发送,我需要发送文件   BODY

我的必需签名是

public class SomeModel {
    public string username { get; set; }
    public dynamic file { get; set; } //<-- Wonder if this is right way ?
}

0 个答案:

没有答案