2015-11-23 39 views
3
上傳FORMDATA對象

我是新來的角的js,並希望用圖像提交的multipart/form-data的,它是$ http.post()方法只支持JSON格式,所以我想轉換form數據對象轉換成json格式,如何使用AngularJS

$scope.SubmitForm=function() 
{ 
    url = siteurl + '/admin/' + $scope.module + '/add'; 

    var form=document.getElementById("addForm"); 
    var formData=new FormData(form); 

    $http({ 
     url  : url, 
     method : "POST", 
     data : formData, 
    }) 
    .then(function(responseText) {     
     alert(JSON.stringify(responseText)); 

    //process data 
    },function(){ 
     alert("hello from error"); 
    }); 

} 

它沒有爲我工作;我試圖讓這個JSON格式的數據,並能正常工作

formData={ 
    "first_name" : $('#first_name').val(), 
    "last_name" : $('#last_name'), 
    //.... 
}; 

,但沒有任何想法,我的圖像文件附加到這個格式;我應該在這裏做什麼來獲得我的工作。

有什麼辦法(功能)FORMDATA對象轉換爲JSON格式

+0

轉換數據[這裏](http://stackoverflow.com/questions/25905608/converting-html-form-data-to-json-object-using-angular-js)。但是爲什麼你不使用ng-model? – Dvir

+0

感謝您的建議,但ng模型不會爲文件工作,我有新的指令,但它很笨重, –

回答

0

通過把兩個線像下面的代碼,在$ HTTP配置行解決(感謝每一個機構) -

 $http({ 
      url  : url, 
      method : "POST", 
      data : formData, 
      transformRequest: angular.identity, // see the angugular js documentation 
      headers : {'Content-Type':undefined}// setting content type to undefined that change the default content type of the angular js 
     }).then(function(responseText){ 

      alert(JSON.stringify(responseText)); 
      ///$scope.tablerows=$scope.totaltablerows; 
      ///$scope.searchFunction(); 
     },function(){ 
      alert("hello from error"); 
     }); 

只是這個工程形成我

1

與角的形式工作時,你真的應該使用ng-model(你可以提供您的示例中的形式?)。它創建一個範圍變量在你的控制器中工作,如果它已經被定義,你將有兩種方式綁定...例如,因爲你的表單不存在我會做這樣的事情,這是簡化的(並沒有測試過)...:

<form name="myForm" ng-submit="SubmitForm()"> 
    Name: <input ng-model="fields.name"> 
    Address: <input ng-model="fields.address"> 
    .... 
</form> 

,並在你的JS控制器...

$scope.submitForm = function(){  
     var data = $scope.fields, 
      url = '/admin/' + $scope.module + '/add'; // I assume $scope.module is available from elsewhere... 

     $http.post(url, data).then(function(resp){ 
     // do stuff... 

     });   
    } 

還有更多的信息在這裏... https://docs.angularjs.org/api/ng/directive/ngModel和W3Schools的有一些例子:http://www.w3schools.com/angular/angular_forms.asp

+0

這不回答OP的問題。 – jakerella

-1

,應當構建像這樣:

var form = document.getElementById('addForm'); 
    var fd = new FormData(form); 
    var file = this.files[0];  
    fd.append("afile", file); 
    // These way you add extra parameters 
    fd.append("first_name", $('#first_name').val()); 
    fd.append("last_name", $('#last_name').val()); 

參考例子 - from github