搜索
您的当前位置:首页正文

Angularjs实现多图片上传预览功能

2020-11-27 来源:爱go旅游网

最近要实现一个多图片上传的预览功能,网上有很多例子大多不太完整,我就把他们的整合了下并且加了一些功能和界面,我们只需要调用一条指令就可以实现,但传给后台还需要额外的代码,会在后面controller里介绍。不知道封装的是否符合标准,还希望大家一起讨论下,如果有时间封装下Angular4的图片上传和预览分享给大家。

图片上传的预览,我们最主要解决的是拿到input的on-change事件,再是读取图片,读取图片我们需要用到FileReader。

我们先写一个读取图片的服务,这是网上的一位大佬写的,我就直接拿了过来

/**
 * 图片上传获取返回的url
 */
 app .factory('fileReader', ["$q", "$log", function($q, $log){
 var onLoad = function(reader, deferred, scope) {
 return function () {
 scope.$apply(function () {
 deferred.resolve(reader.result);
 });
 };
 };

 var onError = function (reader, deferred, scope) {
 return function () {
 scope.$apply(function () {
 deferred.reject(reader.result);
 });
 };
 };

 var getReader = function(deferred, scope) {
 var reader = new FileReader(); //fileReader
 reader.onload = onLoad(reader, deferred, scope);
 reader.onerror = onError(reader, deferred, scope);
 return reader;
 };

 var readAsDataURL = function (file, scope) {
 var deferred = $q.defer();
 var reader = getReader(deferred, scope); 
 reader.readAsDataURL(file); 
 return deferred.promise;

 };

 return {
 readAsDataUrl: readAsDataURL 
 };
}])

我们现在有了图片的读取,我们再来搞定图片的on-change事件

/**
 * 图片上传预览
 */
app .directive('file', ['$parse', 'fileReader', function ($parse, fileReader) { 
 return {
 restrict: 'A',
 link: function(scope, element, attrs, ngModel) {

 var model = $parse(attrs.file);
 var modelSetter = model.assign;
 console.log(modelSetter)
 element.bind('change', function(event){
 scope.$apply(function(){
 modelSetter(scope, element[0].files[0]);
 });
 //附件预览 
 scope.imgupload = (event.srcElement || event.target).files[0];
 getFile(scope.imgupload, scope);

 //获得预览图地址并且把file对象放入上传合集内
 function getFile (imgupload, scope) {
 if(!imgupload) {
 return;
 }
 fileReader.readAsDataUrl(imgupload, scope)
 .then(function(result) {
 scope.imgshows.push(result)
 var file = document.querySelector('input[type=file]').files[0];
 scope.uploadimgs.push(file)//这里是放着传给后台的数据file,下面controller的时候会有
 });
 };
 });
 }
 };
 }]) 

这里就是提供上传图片预览的样式,还有预览图删除的功能

app .directive('uploadimg', function () { 
 return {
 restrict: 'E', 
 scope: {
 uploadimgs: "="
 },
 templateUrl: './js/directives/uploadimg/uploadimg.html', 
 link: function(scope, element, attrs) {
 scope.imgshows = []//预览图片合集放的是src 
 scope.uploadimg_del = function(index,imgs) { 
 scope.imgshows.splice(index,1);
 scope.uploadimgs.splice(index,1);
 }
 }
 }
}) 
<style type="text/css">
.fileupload {
 width: 100px;
 height: 100px;
 border: 1px dotted #ccc;
 display: inline-block;
}
.fileupload-icon {
 font-size:32px;
 position: absolute;
 top: 50%;
 left: 50%;
 transform: translate(-50%,-50%);
}
</style>
<div>
 <div class="fileupload pos-rlt" ng-repeat="imageSrc in imgshows">
 <img ng-src="{{imageSrc}}" style="max-width:200px;max-height:300px;margin:0 auto; display:block;" class="pos-rlt" width=100%; height=100%;/>
 <i class="icon ion-close-circled" style="position: absolute; top:5px; right: 5px" ng-click="uploadimg_del($index, imgshows)"></i>
 </div>
 <div class="fileupload pos-rlt clear" >
 <i class="icon ion-plus-round fileupload-icon"></i>
 <input type="file" style="display:inline-block; width: 100%; height: 100%; opacity:0" name="upload_img" file="upload_img" placeholder="选择图片" accept="image/png,image/gif,image/jpeg,image/jpg" >
 </div>
</div>
</label>

最后的调用也很简单
我们只需要在2个地方加代码一个是在界面,一个是在Controller里

<uploadimg uploadimgs="uploadimgs"></uploadimg>

这个是在Controller里的,这是用来传给后台的数据集合,我们需要传给后台的是file对象

$scope.uploadimgs = []//上传图片合集放的是file对象

如何传给后台呢,直接附上代码,其实不难

$scope.save = function() { 
 var Fromdata = {
 'name': $scope.form.name,
 'desc': $scope.form.descr,
 'price': $scope.form.price,
 'status': $scope.form.status?1:0,

 }
 var uploadData = createFromData(Fromdata)
 for(var i = 0; i < $scope.uploadimgs.length; i++) {
 uploadData.append('upload_imgs', $scope.uploadimgs[i])
 }

 $http({
 method:'POST',
 url:"后台地址",
 data: fd,
 headers: {'Content-Type':undefined},
 transformRequest: angular.identity
 })
 .success( function(response){
 //上传成功的操作

 });

 } 

//构造FormData
//@param 是一个对象
function createFromData(Fromdata) {
 var fd = new FormData();
 for(key in Fromdata) {
 fd.append(key,Fromdata[key]); 
 }
 return fd
}

最后给大家看下预览图

Top