2016-07-28 48 views
0

我試圖上傳使用Angularjs和的WebAPI多個文件.. 這是我的HTML表格:如何調用控制器的方法在文件上傳使用Angularjs的WebAPI

<body ng-app="fupApp"> 

    <div ng-controller="fupController"> 
     <input type="file" id="file" name="file" multiple 
       onchange="angular.element(this).scope().getFileDetails(this)" /> 

     <input type="button" ng-click="uploadFiles()" value="Upload" /> 

     <!--ADD A PROGRESS BAR ELEMENT.--> 
     <p><progress id="pro" value="0"></progress></p> 
    </div> 

</body> 

下面是多文件上傳我的Angularjs代碼(fileupload.js):

var myApp = angular.module('fupApp', []); 

myApp.controller('fupController', function ($scope) { 

    // GET THE FILE INFORMATION. 
    $scope.getFileDetails = function (e) { 
     debugger; 
     $scope.files = []; 
     $scope.$apply(function() { 
      debugger; 
      // STORE THE FILE OBJECT IN AN ARRAY. 
      for (var i = 0; i < e.files.length; i++) { 
       $scope.files.push(e.files[i]) 
      } 

     }); 
    }; 

    // NOW UPLOAD THE FILES. 
    $scope.uploadFiles = function() { 
     debugger; 
     //FILL FormData WITH FILE DETAILS. 
     var data = new FormData(); 

     for (var i in $scope.files) { 
      data.append("uploadedFile", $scope.files[i]); 
     } 

     // ADD LISTENERS. 
     var objXhr = new XMLHttpRequest(); 
     objXhr.addEventListener("progress", updateProgress, false); 
     objXhr.addEventListener("load", transferComplete, false); 

     // SEND FILE DETAILS TO THE API. 
     objXhr.open("POST","MailRoute/getDataForUploadFiles"); 

     objXhr.send(data); 
    } 

    // UPDATE PROGRESS BAR. 
    function updateProgress(e) { 
     debugger; 
     if (e.lengthComputable) { 
      document.getElementById('pro').setAttribute('value', e.loaded); 
      document.getElementById('pro').setAttribute('max', e.total); 
     } 
    } 

    // CONFIRMATION. 
    function transferComplete(e) { 
     debugger; 
     alert("Files uploaded successfully."); 
    } 
}); 

這裏是我的WebAPI功能:

public async Task<HttpResponseMessage> getDataForUploadFiles() 
       { 
       } 

但如何讀取文件deatils,並從控制器的方法訪問文件的詳細信息(getDataForUploadFiles)

+0

你是否在'$ scope.files'對象中獲取文件? – Venky

+0

您將'Route'指定爲'getDataForUploadFiles'並調用'objXhr.open(「POST」,「/ file_upload」);'這顯然是錯誤的。 – Venky

+0

您可以利用angularjs功能輕鬆上傳文件。 http://stackoverflow.com/questions/24443246/angularjs-how-to-upload-multipart-form-data-and-a-file – Venky

回答

0

試試這個

<div ng-controller="Ctrl"> 
    <input type="file" file-upload multiple/> 
    <ul> 
     <li ng-repeat="file in files">{{file.name}}</li> 
    </ul> 
    </div> 

控制器代碼

function Ctrl($scope, $http) { 

    //a simple model to bind to and send to the server 
    $scope.model = { 
     name: "", 
     comments: "" 
    }; 

    //an array of files selected 
    $scope.files = []; 

    //listen for the file selected event 
    $scope.$on("fileSelected", function (event, args) { 
     $scope.$apply(function() {    
      //add the file object to the scope's files collection 
      $scope.files.push(args.file); 
     }); 
    }); 

    //the save method 
    $scope.save = function() { 
     $http({ 
      method: 'POST', 
      url: "/MailRoute/getDataForUploadFiles", 
      //IMPORTANT!!! You might think this should be set to 'multipart/form-data' 

      headers: { 'Content-Type': false }, 

      transformRequest: function (data) { 
       var formData = new FormData(); 

       formData.append("model", angular.toJson(data.model)); 
       //now add all of the assigned files 
       for (var i = 0; i < data.files; i++) { 
        //add each file to the form data and iteratively name them 
        formData.append("file" + i, data.files[i]); 
       } 
       return formData; 
      }, 
      //Create an object that contains the model and files which will be transformed 
      // in the above transformRequest method 
      data: { model: $scope.model, files: $scope.files } 
     }). 
     success(function (data, status, headers, config) { 
      alert("success!"); 
     }). 
     error(function (data, status, headers, config) { 
      alert("failed!"); 
     }); 
    }; 
}; 

處理數據的服務器端

public async Task<HttpResponseMessage> getDataForUploadFiles() 
{ 
    if (!Request.Content.IsMimeMultipartContent()) 
    { 
     throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); 
    } 

    var root = HttpContext.Current.Server.MapPath("~/App_Data/Temp/FileUploads"); 
    Directory.CreateDirectory(root); 
    var provider = new MultipartFormDataStreamProvider(root); 
    var result = await Request.Content.ReadAsMultipartAsync(provider); 
    if (result.FormData["model"] == null) 
    { 
     throw new HttpResponseException(HttpStatusCode.BadRequest); 
    } 

    var model = result.FormData["model"]; 
    //TODO: Do something with the json model which is currently a string 



    //get the files 
    foreach (var file in result.FileData) 
    {     
     //TODO: Do something with each uploaded file 
    } 

    return Request.CreateResponse(HttpStatusCode.OK, "success!"); 
} 
+0

xhr.setRequestHeader 「Content-Type」,「multipart/form-data」); xhr.setRequestHeader(「X-File-Name」,uf.name);不起作用 –

+0

確保您的API支持CORS,並且該授權是被設置的允許的請求標頭。當您向端點發送OPTIONS請求時,您的API應該使用以下響應標頭進行響應: – Venky

+0

也嘗試將「Content-Type」更改爲「content-type」,儘管它們是「不區分大小寫的」。值得一試。 – Venky

相關問題