这是我的HTML表单:
<form name="myForm" ng-submit="">
<input ng-model='file' type="file"/>
<input type="submit" value='Submit'/>
</form>
我想从本地机器上传一个图像,并想读取上传文件的内容。所有这些我都想用AngularJS来做。
当我试图打印$scope的值时。文件是未定义的。
这是我的HTML表单:
<form name="myForm" ng-submit="">
<input ng-model='file' type="file"/>
<input type="submit" value='Submit'/>
</form>
我想从本地机器上传一个图像,并想读取上传文件的内容。所有这些我都想用AngularJS来做。
当我试图打印$scope的值时。文件是未定义的。
当前回答
使用简单指令的示例(ng-file-model):
.directive("ngFileModel", [function () {
return {
$scope: {
ngFileModel: "="
},
link: function ($scope:any, element, attributes) {
element.bind("change", function (changeEvent:any) {
var reader = new FileReader();
reader.onload = function (loadEvent) {
$scope.$apply(function () {
$scope.ngFileModel = {
lastModified: changeEvent.target.files[0].lastModified,
lastModifiedDate: changeEvent.target.files[0].lastModifiedDate,
name: changeEvent.target.files[0].name,
size: changeEvent.target.files[0].size,
type: changeEvent.target.files[0].type,
data: changeEvent.target.files[0]
};
});
}
reader.readAsDataURL(changeEvent.target.files[0]);
});
}
}
}])
并使用FormData在函数中上传文件。
var formData = new FormData();
formData.append("document", $scope.ngFileModel.data)
formData.append("user_id", $scope.userId)
所有学分都归 https://github.com/mistralworks/ng-file-model
我遇到了一个小问题,你可以在这里查看: https://github.com/mistralworks/ng-file-model/issues/7
最后,这里是一个分叉的回购:https://github.com/okasha93/ng-file-model/blob/patch-1/ng-file-model.js
其他回答
超文本标记语言
<input type="file" id="file" name='file' onchange="angular.element(this).scope().profileimage(this)" />
添加'profileimage()'方法到你的控制器
$scope.profileimage = function(selectimage) {
console.log(selectimage.files[0]);
var selectfile=selectimage.files[0];
r = new FileReader();
r.onloadend = function (e) {
debugger;
var data = e.target.result;
}
r.readAsBinaryString(selectfile);
}
<input type=file>元素默认不使用ng-model指令。它需要一个自定义指令:
使用ng-model1的select-ng-files指令的工作演示
angular.module("app",[]); angular.module("app").directive("selectNgFiles", function() { return { require: "ngModel", link: function postLink(scope,elem,attrs,ngModel) { elem.on("change", function(e) { var files = elem[0].files; ngModel.$setViewValue(files); }) } } }); <script src="//unpkg.com/angular/angular.js"></script> <body ng-app="app"> <h1>AngularJS Input `type=file` Demo</h1> <input type="file" select-ng-files ng-model="fileList" multiple> <h2>Files</h2> <div ng-repeat="file in fileList"> {{file.name}} </div> </body>
美元http。从FileList中post
$scope.upload = function(url, fileList) {
var config = { headers: { 'Content-Type': undefined },
transformResponse: angular.identity
};
var promises = fileList.map(function(file) {
return $http.post(url, file, config);
});
return $q.all(promises);
};
当发送带有File对象的POST时,重要的是设置'Content-Type': undefined。然后XHR发送方法将检测File对象并自动设置内容类型。
您的文件和json数据同时上传。
// FIRST SOLUTION var _post = function (file, jsonData) { $http({ url: your url, method: "POST", headers: { 'Content-Type': undefined }, transformRequest: function (data) { var formData = new FormData(); formData.append("model", angular.toJson(data.model)); formData.append("file", data.files); return formData; }, data: { model: jsonData, files: file } }).then(function (response) { ; }); } // END OF FIRST SOLUTION // SECOND SOLUTION // If you can add plural file and If above code give an error. // You can try following code var _post = function (file, jsonData) { $http({ url: your url, method: "POST", headers: { 'Content-Type': undefined }, transformRequest: function (data) { var formData = new FormData(); formData.append("model", angular.toJson(data.model)); for (var i = 0; i < data.files.length; i++) { // add each file to // the form data and iteratively name them formData.append("file" + i, data.files[i]); } return formData; }, data: { model: jsonData, files: file } }).then(function (response) { ; }); } // END OF SECOND SOLUTION
我们使用了HTML, CSS和AngularJS。下面的例子展示了如何使用AngularJS上传文件。
<html>
<head>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>
<body ng-app = "myApp">
<div ng-controller = "myCtrl">
<input type = "file" file-model = "myFile"/>
<button ng-click = "uploadFile()">upload me</button>
</div>
<script>
var myApp = angular.module('myApp', []);
myApp.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]);
});
});
}
};
}]);
myApp.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file, uploadUrl){
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
})
.error(function(){
});
}
}]);
myApp.controller('myCtrl', ['$scope', 'fileUpload', function($scope, fileUpload){
$scope.uploadFile = function(){
var file = $scope.myFile;
console.log('file is ' );
console.dir(file);
var uploadUrl = "/fileUpload";
fileUpload.uploadFileToUrl(file, uploadUrl);
};
}]);
</script>
</body>
</html>
最简单的是使用HTML5 API,即FileReader
HTML非常简单:
<input type="file" id="file" name="file"/>
<button ng-click="add()">Add</button>
在你的控制器中定义'add'方法:
$scope.add = function() {
var f = document.getElementById('file').files[0],
r = new FileReader();
r.onloadend = function(e) {
var data = e.target.result;
//send your binary data via $http or $resource or do anything else with it
}
r.readAsBinaryString(f);
}
浏览器兼容性
桌面浏览器
Edge 12, Firefox(Gecko) 3.6(1.9.2), Chrome 7, Opera* 12.02, Safari 6.0.2
移动浏览器
Firefox(壁虎)32, Chrome 3, 歌剧* 11.5, Safari 6.1
注意:readAsBinaryString()方法已弃用,应该使用readAsArrayBuffer()代替。