2016-12-12 61 views
0

這是張貼在這裏發送數據到後HTTP是我的代碼如何上傳的文件分配給對象的屬性和angularjs

HTML: -

<form> 
    <input type="file" name="fileUpload" file-model="obj.file"> 
    <input type="text" name="name" ng-model="obj.name"> 
    <input type="text" name="city" ng-model="obj.city"> 
<button type="button" ng-click="uploadFile()"></button> 
</form> 

指令讀取文件時選擇文件格式HTML:---

angular.module('iscopeNewUiApp.appcore') 
.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]); 
       }); 
      }); 
     } 
    }; 
}]); 

控制器代碼這種形式的數據發送到HTTP POST:---

內部控制存在uploadFile()方法

$scope.uploadFile = function(){ 
var file,name,city; 
file = $scope.obj.file; 
name = $scope.obj.name; 
city = $scope.obj.city; 
var fd = new FormData(); 
var attribute = "<attributes> 
        <name>name</name> 
        <city>city</city> 
       </attributes>" 

fd.append('executefile', file); 
fd.append('attributes', attributes); 

$http.post("http://hyperion.iscope.innominds:8181/iscope-metadata/rest/resource/uploadfile", fd, { 
        transformRequest: angular.identity, 
        headers: { 'Content-Type': undefined } 
       }).success(function(resp){ 
        console.log(resp); 
       }).error(function(error){ 
        console.log(error); 
       }) 
} 

其實我想將數據發送這樣

fd = {'executefile': file,'attributes', <attributes><name>sdsd</name><city>sdsd</city></attributes>}; 


but when i tried with above code it is going like below 

    ------WebKitFormBoundaryo2MKUAGw2aE8CGU6 
Content-Disposition: form-data; name="executefile"; filename="dropDownWithLiveSearch.html" 
Content-Type: text/html 


------WebKitFormBoundaryo2MKUAGw2aE8CGU6 
Content-Disposition: form-data; name="attributes" 

<attributes><name>sdsd</name><city>sdsd</city></attributes> 
------WebKitFormBoundaryo2MKUAGw2aE8CGU6-- 

我這裏是https://jsfiddle.net/ZG9re/6400/

任何一個可以建議我如何發送文件剩餘的數據在一個對象中?

回答

1

有很多由社區編寫的Angular模塊來完成文件上傳。這兩對老版本瀏覽器的明確支持:

一對夫婦更多的選擇:

還有其他一些選項:

如果你不希望使用任何那些你可以編寫自己的使用文件API:

var formData = new FormData(); 
formData.append("file", $scope.file); 

然後添加到您的AJAX調用:

data: { 
     formdata 
    } 
相關問題