首頁 >web前端 >H5教程 >Angular下H5多張上傳圖片的方法

Angular下H5多張上傳圖片的方法

不言
不言原創
2018-06-11 16:31:552070瀏覽

本文跟大家分享在使用angular上傳圖片的功能,在開發過程中遇到很多問題,最後都解決了,今天小編給大家介紹下Angular下H5上傳圖片的方法(可多張上傳),非常不錯,需要的朋友參考下

最近做的專案中用到了angular下上傳圖片功能,在做的過程中遇到了許多問題,最終都得以解決

angular上傳時和普通上傳時過程差不多,只不過是要不一些東西轉化為angular的東西。

1.ng-file-select,指令angular是沒此功能的,其實也是轉換成了change事件,不多說,直接上程式碼

angular.module('myApp')
.directive('ngFileSelect', [ '$parse', '$timeout', function($parse, $timeout) {
    return function(scope, elem, attr) {
      var fn = $parse(attr['ngFileSelect']);
      elem.bind('change', function(evt) {
        var files = [], fileList, i;
        fileList = evt.target.files;
        if (fileList != null) {
          for (i = 0; i < fileList.length; i++) {
            files.push(fileList.item(i));
          }
        }
        $timeout(function() {
          fn(scope, {
            $files : files,
            $event : evt
          });
        });
      });
    };
  }])

2.服務上傳檔案前預覽並壓縮圖片功能

//上传文件预览
angular.module(&#39;myServers&#39;,[])
  .factory(&#39;fileReader&#39;, [&#39;$q&#39;, &#39;$log&#39;, function($q, $log) {
    var dataURItoBlob = function(dataURI) { 
      // convert base64/URLEncoded data component to raw binary data held in a string 
      var byteString; 
      if (dataURI.split(&#39;,&#39;)[0].indexOf(&#39;base64&#39;) >= 0) 
        byteString = atob(dataURI.split(&#39;,&#39;)[1]); 
      else 
        byteString = unescape(dataURI.split(&#39;,&#39;)[1]); 
      // separate out the mime component 
      var mimeString = dataURI.split(&#39;,&#39;)[0].split(&#39;:&#39;)[1].split(&#39;;&#39;)[0]; 
      // write the bytes of the string to a typed array 
      var ia = new Uint8Array(byteString.length); 
      for (var i = 0; i < byteString.length; i++) { 
        ia[i] = byteString.charCodeAt(i); 
      } 
      return new Blob([ia], { 
        type: mimeString 
      }); 
    }; 
    var onLoad = function(reader, deferred, scope,file) {
      return function() {
        scope.$apply(function() {
           var img = new Image();
          //前端压缩图片
          img.onload = function(){ 
            //resize the image using canvas 
            var canvas = document.createElement("canvas"); 
            var ctx = canvas.getContext("2d"); 
            var width = img.width; 
            var height = img.height; 
            var MAX_WIDTH = width>2500 ? width/2 : 2500; 
            var MAX_HEIGHT = height>2500 ? height/2 : 2500;
            if (width > height) { 
              if (width > MAX_WIDTH) { 
                height *= MAX_WIDTH / width; 
                width = MAX_WIDTH; 
              } 
            } else { 
              if (height > MAX_HEIGHT) { 
                width *= MAX_HEIGHT / height; 
                height = MAX_HEIGHT; 
              } 
            }
            canvas.width = width ; 
            canvas.height = height; 
            ctx.drawImage(img, 0, 0, width, height); 
            var dataURL = canvas.toDataURL(&#39;image/jpeg&#39;, 1);
            var blob = dataURItoBlob(dataURL); 
            if(blob.size > 2000 * 1024){
              dataURL = canvas.toDataURL(&#39;image/jpeg&#39;, .2);
            }else if(blob.size > 1000 * 1024){
              dataURL = canvas.toDataURL(&#39;image/jpeg&#39;, .5);
            }else{
              dataURL = canvas.toDataURL(&#39;image/jpeg&#39;, .8);
            }
            blob = dataURItoBlob(dataURL);
            deferred.resolve(blob);
          }
          img.src = URL.createObjectURL(file);
        });
      };
    };
    var onError = function(reader, deferred, scope) {
      return function() {
        scope.$apply(function() {
          deferred.reject(reader.result);
        });
      };
    };
    var onProgress = function(reader, scope) {
      return function(event) {
        scope.$broadcast("fileProgress", {
          total: event.total,
          loaded: event.loaded
        });
      };
    };
    var getReader = function(deferred, scope, file) {
      var reader = new FileReader();
      reader.onload = onLoad(reader, deferred, scope,file);
      reader.onerror = onError(reader, deferred, scope);
      reader.onprogress = onProgress(reader, scope);
      return reader;
    };
    var readAsDataURL = function(file, scope) {
      var deferred = $q.defer();
      var reader = getReader(deferred, scope,file);
      reader.readAsDataURL(file);
      return deferred.promise;
    };
    return {
      readAsDataUrl: readAsDataURL
    };
  }]);


這裡說明一下,部分程式碼是參考別人的程式碼(http://blog.csdn.net/zx007fack/article/details/41073601 ),但是對其​​中內容做了修改,因為用原來的程式碼,如果不加前端壓縮功能是正常的,前端壓縮的話因為要用到canvas, 直接用reader.result在ios上圖片的寬高拿到的直接是0,android上是可以的,具體原因不是很確定是不是base64的問題,所以我又直接把file傳了進來,然後用原生js的方法新建圖片元素拿到寬高,再用Canvas進行壓縮,最後轉成blob,透過formData傳給後台。

3.controller代碼

//选择图片后执行的方法
    $scope.fileArr = [];
    $scope.imgSrcArr = [];var i = 0; //为ios上图片都为image时添加序号
    $rootScope.onFileSelect = function(files, event) {
      //预览上传图片开始
      $rootScope.startLoading();
      var $this = angular.element(event.target);
      angular.forEach(files, function(value, index) {
        var fileIn = value;
        var fileInName = fileIn.name;
        var fileType = fileInName.substring(fileInName.lastIndexOf(".") + 1, fileInName.length);
        //解决ios下所有图片都为image.jpg的bug
        if(fileIn) {
          fileInName = fileInName.split(&#39;.&#39;)[0] + i + &#39;.&#39; + fileType;
          i++;
        }
        attachvo.push({
          name: fileInName,
          type: fileType
        });
        fileReader.readAsDataUrl(fileIn, $scope)
          .then(function(result) {
            result.name = fileInName;
            $scope.fileArr.push(result);
            $scope.imgSrcArr.push(URL.createObjectURL(result));
              //每次上传后清空file框,确保每次都能调用change事件
            document.querySelector(&#39;.upload&#39;).reset();
          });
        $scope.$on(&#39;fileProgress&#39;, function(event, data) {
          if(data.total == data.loaded) {
            $timeout(function() {
              //上传图片结束
              $rootScope.endLoading();
            }, 200)
          }
        });      
      });
      $rootScope.showAttachment = false;
    };return false;
    }

這裡處理了下圖片,在名字上加了序號,因為在ios上每次選擇的圖片名字都叫image,查找了很多資料,說是safari的bug,後面版本才會解決,暫時只能這樣解決了。循環是上傳多張圖片

3.html程式碼

<ul class="upload-view-ul">
    <li ng-repeat="src in imgSrcArr" class="pull-left" ng-click="delCurUpload(src)" 
      ng-class="{&#39;row-last&#39;: (($index+1) % 5==0)}">
      <span>x</span>
      <em ng-if=&#39;nrc&#39;>{{formData.attachvo[$index].attachmentType}}</em>
      <img ng-src="{{src}}">
    </li>
    <p class="attachment" pop-type-select ng-if="nrc">+</p>
    <p class="attachment" ng-if="!nrc">
      +
      <form class="upload">
        <input type="file" name="file[]" ng-file-select="onFileSelect($files, $event)" multiple>
      </form>
    </p>
  </ul>

4.順便把formdata時程式碼貼一下,採用H5上傳圖片的方式

this.FormdataPost = function(pathUrl, formId, formData, files) {
    var fd = new FormData();
    fd.append(&#39;formId&#39;, formId);
    if(files && angular.isArray(files)) {
      files.forEach(function(item) {
        fd.append(&#39;file&#39;, item, item.name);
      });
    }
    fd.append(&#39;formData&#39;, angular.toJson(formData, true));
    var httpConfig = {
      headers: {
        &#39;Authorization&#39;: &#39;Bearer &#39; + this.token,
        &#39;Content-Type&#39;: undefined
      },
      transformRequest: angular.identity
    };
    return $http.post(rootUrl + pathUrl, fd, httpConfig).then(function(data) {
      return data;
    }).catch(function(error) {
      $rootScope.interfaceName = pathUrl;
      $rootScope.setNewWortStatus({
        status: error.status,
        errInfo: error.data && error.data.statusInfo || &#39;&#39;
      });
      return error;
    });
  }

思路有一點混亂,不知道講清楚了沒有,想起來再添加吧

以上就是本文的全部內容,希望對大家的學習有所幫助,更多相關內容請關注PHP中文網!

相關推薦:

H5手機端圖片上傳外掛程式碼

#H5實作上傳本機圖片並且能夠預覽的功能程式碼

以上是Angular下H5多張上傳圖片的方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn