2016-05-26 113 views
0

我正在使用這個指令(ng--file-upload)來上傳圖片。
我需要包含圖像文件到POST到ASP.NET Web API,但我沒有任何成功。
這是我的服務器上的方法:無法上傳圖片文件從ng-file-upload到web api

public async Task<HttpResponseMessage> SaveData([FromBody]PostModel data) 

當我發佈的數據(從JS角)的所有資料都在這兒,除了上傳文件:

$http({ 
      method: 'POST', 
      url: path, 
      data: data, 
      file: photoFile 
     }).then(function... 

我試圖把它的數據還,但它始終爲空。
如何發佈並獲取Web api上的圖像文件?

正如我得到的迴應:

"Invalid 'HttpContent' instance provided. It does not have a content type header starting with 'multipart/'. 
Parameter name: content" 

在此行中:

var provider = new MultipartMemoryStreamProvider(); 
      await Request.Content.ReadAsMultipartAsync(provider); 

var data = {    
      "Username": $scope.username, 
      transformRequest: angular.identity, 
      headers: { 'Content-Type': undefined } 
     }; 

     var fd = new FormData(); 
     fd.append('file', $scope.photoFile); 

     $http({ 
      method: 'POST', 
      url: 'path', fd, 
      data: data 
     }).the 
+0

您可以使用'Upload.upload()'服務發送文件。閱讀文檔。 – danial

回答

1

使用FormData API

HTML:

<div class="button" ngf-select="upload($file)">Upload on file select</div> 

控制器:

$scope.upload = function (file) { 
    var fd = new FormData(); 
    fd.append('file', file); 

    //Append other data 
    //angular.forEach(data,function(v,k){ 
    // fd.append(k,v); 
    //}); 

    $http.post('your-upload-url', fd, { 
     transformRequest: angular.identity, 
     headers: {'Content-Type': undefined} 
    }) 
    .then(function(res){ 
     // get upload res 
    }); 
}; 
+0

但是我怎樣才能獲得Web API端的文件? – 1110

+0

對不起,我認爲這是一個尖銳的問題....不擅長c#,但你可以檢查[this](http://www.asp.net/web-api/overview/advanced/sending-html-form -data-part-2) –

+0

我更新了發送數據的問題,正如你所建議的,你可能知道爲什麼我從錯誤中得到錯誤? – 1110