search
HomeWeb Front-endH5 TutorialHow to upload multiple H5 images in 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
          });
        });
      });
    };
  }])

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


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;
    }

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  src="/static/imghwm/default1.png"  data-src="{{src}}"  class="lazy"  ng- alt="How to upload multiple H5 images in Angular" >
    </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. 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;
    });
  }

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
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
H5: The Future of Web Content and DesignH5: The Future of Web Content and DesignMay 01, 2025 am 12:12 AM

H5 (HTML5) will improve web content and design through new elements and APIs. 1) H5 enhances semantic tagging and multimedia support. 2) It introduces Canvas and SVG, enriching web design. 3) H5 works by extending HTML functionality through new tags and APIs. 4) Basic usage includes creating graphics using it, and advanced usage involves WebStorageAPI. 5) Developers need to pay attention to browser compatibility and performance optimization.

H5: New Features and Capabilities for Web DevelopmentH5: New Features and Capabilities for Web DevelopmentApr 29, 2025 am 12:07 AM

H5 brings a number of new functions and capabilities, greatly improving the interactivity and development efficiency of web pages. 1. Semantic tags such as enhance SEO. 2. Multimedia support simplifies audio and video playback through and tags. 3. Canvas drawing provides dynamic graphics drawing tools. 4. Local storage simplifies data storage through localStorage and sessionStorage. 5. The geolocation API facilitates the development of location-based services.

H5: Key Improvements in HTML5H5: Key Improvements in HTML5Apr 28, 2025 am 12:26 AM

HTML5 brings five key improvements: 1. Semantic tags improve code clarity and SEO effects; 2. Multimedia support simplifies video and audio embedding; 3. Form enhancement simplifies verification; 4. Offline and local storage improves user experience; 5. Canvas and graphics functions enhance the visualization of web pages.

HTML5: The Standard and its Impact on Web DevelopmentHTML5: The Standard and its Impact on Web DevelopmentApr 27, 2025 am 12:12 AM

The core features of HTML5 include semantic tags, multimedia support, offline storage and local storage, and form enhancement. 1. Semantic tags such as, etc. to improve code readability and SEO effect. 2. Simplify multimedia embedding with labels. 3. Offline storage and local storage such as ApplicationCache and LocalStorage support network-free operation and data storage. 4. Form enhancement introduces new input types and verification properties to simplify processing and verification.

H5 Code Examples: Practical Applications and TutorialsH5 Code Examples: Practical Applications and TutorialsApr 25, 2025 am 12:10 AM

H5 provides a variety of new features and functions, greatly enhancing the capabilities of front-end development. 1. Multimedia support: embed media through and elements, no plug-ins are required. 2. Canvas: Use elements to dynamically render 2D graphics and animations. 3. Local storage: implement persistent data storage through localStorage and sessionStorage to improve user experience.

The Connection Between H5 and HTML5: Similarities and DifferencesThe Connection Between H5 and HTML5: Similarities and DifferencesApr 24, 2025 am 12:01 AM

H5 and HTML5 are different concepts: HTML5 is a version of HTML, containing new elements and APIs; H5 is a mobile application development framework based on HTML5. HTML5 parses and renders code through the browser, while H5 applications need to run containers and interact with native code through JavaScript.

The Building Blocks of H5 Code: Key Elements and Their PurposeThe Building Blocks of H5 Code: Key Elements and Their PurposeApr 23, 2025 am 12:09 AM

Key elements of HTML5 include,,,,,, etc., which are used to build modern web pages. 1. Define the head content, 2. Used to navigate the link, 3. Represent the content of independent articles, 4. Organize the page content, 5. Display the sidebar content, 6. Define the footer, these elements enhance the structure and functionality of the web page.

HTML5 and H5: Understanding the Common UsageHTML5 and H5: Understanding the Common UsageApr 22, 2025 am 12:01 AM

There is no difference between HTML5 and H5, which is the abbreviation of HTML5. 1.HTML5 is the fifth version of HTML, which enhances the multimedia and interactive functions of web pages. 2.H5 is often used to refer to HTML5-based mobile web pages or applications, and is suitable for various mobile devices.

See all articles

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

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.