简易上传图片原生input-file实现方案

时间:2022-08-28 12:01:53

html:

<div class="addImages">

<span class="addImagesText">添加图片({{allImgBaseData.length}}/5)</span>
<div class="addImagesSample" ng-repeat="item in allImgBaseData track by $index">
<span> 
<img ng-src='{{item}}'>
<i class='icon ion-close-circled removeImg' ng-click='removeImg($index)'></i>
</span>
</div>
<label class="addImagesButton" for="inputs" ng-if="allImgBaseData.length!=5">
  <i class="icon ion-ios-plus-empty"></i>
  <input accept="image/*" type="file" accept=".gif,.jpg,.jpeg,.png" onchange="angular.element(this).scope().fileChange(this)">
  </label>

</div>




js:

//上传图片
$scope.allImgBaseData = []; //所有图片的base码集合
$scope.fileChange = function(fil){
var filtext = fil.files[0];
if(parseInt(filtext.size) / 1024 > 1024){
$hctopalert.show({
text: "仅可以上传1M以内的图片"
});
return false;
};
if($scope.allImgBaseData.length>=5){
$hctopalert.show({
text: "图片已达到上限"
});
return false;
};
var reader = new FileReader();
reader.readAsDataURL(filtext);
reader.onload = function() {
var strcode = reader.result;
$scope.allImgBaseData.push(strcode); //储存到数组里
$scope.$apply();
}
};
//选出图片可删除功能
$scope.removeImg = function(index){
$scope.allImgBaseData.splice(index,1);
};