Home Web Front-end H5 Tutorial How to upload multiple H5 images in Angular

How to upload multiple H5 images in Angular

Jun 11, 2018 pm 04:31 PM
angular

This article will share with you the function of uploading images using angular. During the development process, I encountered many problems and they were finally solved. Today I will introduce to you the method of uploading images in H5 under Angular (multiple images can be uploaded). Very good, friends who need it can refer to it

The function of uploading pictures under angular was used in a recent project. I encountered many problems during the process, and they were finally solved

When uploading in angular The process is similar to the normal upload process, except that some things need to be converted into angular things.

1.ng-file-select, the instruction angular does not have this function. In fact, it is converted into a change event. Not much to say, just go to the code

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
          });
        });
      });
    };
  }])
Copy after login

2. Before the service uploads the file Preview and compress image function

//上传文件预览
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
    };
  }]);
Copy after login


Let me explain here, part of the code is based on other people’s code (http://blog.csdn.net/zx007fack/article/details/41073601 ), but the content has been modified, because with the original code, it is normal if the front-end compression function is not added. For front-end compression, because canvas is used, you can directly use reader.result to get the width and height of the image on ios. It is directly 0, which is possible on Android. The specific reason is not sure whether it is a problem with base64, so I directly passed the file in, then used the native js method to create a new image element to get the width and height, and then used Canvas to compress it. , and finally converted into blob, passed to the background through formData.

3.controller code

//选择图片后执行的方法
    $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;
    }
Copy after login

Here we process the picture and add a serial number to the name, because the name of the picture selected every time on ios is called image. I searched a lot of information and said It's a Safari bug that will be solved in later versions, so it can only be solved in this way for the time being. The loop is to upload multiple pictures

3.html code

<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>
Copy after login

4. By the way, paste the formdata code, using the H5 method of uploading pictures

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;
    });
  }
Copy after login

The idea is a bit confusing , I don’t know if I have made it clear, I will add it when I think of it

The above is the entire content of this article. I hope it will be helpful to everyone’s study. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

H5 mobile phone image upload plug-in code

H5 implements the function of uploading local images and previewing them Code

The above is the detailed content of How to upload multiple H5 images in Angular. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Let's talk about metadata and decorators in Angular Let's talk about metadata and decorators in Angular Feb 28, 2022 am 11:10 AM

This article continues the learning of Angular, takes you to understand the metadata and decorators in Angular, and briefly understands their usage. I hope it will be helpful to everyone!

How to install Angular on Ubuntu 24.04 How to install Angular on Ubuntu 24.04 Mar 23, 2024 pm 12:20 PM

Angular.js is a freely accessible JavaScript platform for creating dynamic applications. It allows you to express various aspects of your application quickly and clearly by extending the syntax of HTML as a template language. Angular.js provides a range of tools to help you write, update and test your code. Additionally, it provides many features such as routing and form management. This guide will discuss how to install Angular on Ubuntu24. First, you need to install Node.js. Node.js is a JavaScript running environment based on the ChromeV8 engine that allows you to run JavaScript code on the server side. To be in Ub

An article exploring server-side rendering (SSR) in Angular An article exploring server-side rendering (SSR) in Angular Dec 27, 2022 pm 07:24 PM

Do you know Angular Universal? It can help the website provide better SEO support!

Detailed explanation of angular learning state manager NgRx Detailed explanation of angular learning state manager NgRx May 25, 2022 am 11:01 AM

This article will give you an in-depth understanding of Angular's state manager NgRx and introduce how to use NgRx. I hope it will be helpful to you!

Angular + NG-ZORRO quickly develop a backend system Angular + NG-ZORRO quickly develop a backend system Apr 21, 2022 am 10:45 AM

This article will share with you an Angular practical experience and learn how to quickly develop a backend system using angualr combined with ng-zorro. I hope it will be helpful to everyone!

A brief analysis of how to use monaco-editor in angular A brief analysis of how to use monaco-editor in angular Oct 17, 2022 pm 08:04 PM

How to use monaco-editor in angular? The following article records the use of monaco-editor in angular that was used in a recent business. I hope it will be helpful to everyone!

How to use PHP and Angular for front-end development How to use PHP and Angular for front-end development May 11, 2023 pm 04:04 PM

With the rapid development of the Internet, front-end development technology is also constantly improving and iterating. PHP and Angular are two technologies widely used in front-end development. PHP is a server-side scripting language that can handle tasks such as processing forms, generating dynamic pages, and managing access permissions. Angular is a JavaScript framework that can be used to develop single-page applications and build componentized web applications. This article will introduce how to use PHP and Angular for front-end development, and how to combine them

A brief analysis of independent components in Angular and see how to use them A brief analysis of independent components in Angular and see how to use them Jun 23, 2022 pm 03:49 PM

This article will take you through the independent components in Angular, how to create an independent component in Angular, and how to import existing modules into the independent component. I hope it will be helpful to you!

See all articles