这是我的代码
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 的 Controller 代码:---
Controller 内部有一个 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/
有人可以建议我如何在一个对象中发送文件和剩余数据吗?
最佳答案
社区编写了很多 Angular 模块来进行文件上传。这两个对旧版浏览器有明确的支持:
- https://github.com/leon/angular-upload - 使用 iframe 作为后备
- https://github.com/danialfarid/ng-file-upload - 使用 FileAPI/Flash 作为后备
还有几个选项:
以及其他一些选项:
- https://github.com/nervgh/angular-file-upload/
- https://github.com/uor/angular-file
- https://github.com/twilson63/ngUpload
如果您不想使用其中任何一个,您可以使用 File api 编写自己的:
var formData = new FormData();
formData.append("file", $scope.file);
然后将其添加到您的 ajax 调用中:
data: {
formdata
}
关于javascript - 如何将上传的文件分配给对象的属性并作为数据发送到angularjs中的post http,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41099127/