你的位置:首页 > Java教程

[Java教程]angularjs input上传图片前获取图片的Size


首先我们需要一个指令来追踪input的change。ngChage不适用input[file]。

app.directive("fileread", [function () {
return {
scope: {
selectedFile: "=",
changed: '&'
},
link: function(scope, element, attributes) {
element.bind("change", function(changeEvent) {
scope.$apply(function() {
scope.selectedFile = changeEvent.target.files[0];
// or all selected files:
// scope.fileread = changeEvent.target.files;
console.log('file selected.');
if (scope.changed()) {
scope.changed()(scope.selectedFile);
}
});
});
}
};
}]);

然后在controller里定义file的变量跟change绑定的function。

$scope.showFileSelectBox = function () {
$("#imgSelectInput").click();
};

$scope.imageSelected = function(file) {
var image;

if (file) {

image = new Image();

image.onload = function () {

$scope.editObj.Width = this.width;
$scope.editObj.Height = this.height;
};

image.src = $window.URL.createObjectURL(file);

}
};

然后是html

<button type="button"  ng-click="showFileSelectBox()">上传</button>
<input type="file" accept="image/*" fileread selectedfile="selectedImgFile" id="imgSelectInput" changed="imageSelected" />