Home Web Front-end JS Tutorial Learn to use AngularJS file upload control_AngularJS

Learn to use AngularJS file upload control_AngularJS

May 16, 2016 pm 03:15 PM

Some time ago when I was working on a project, I encountered a need to upload files. The approximate style that needs to be implemented is as follows, see the picture below:

Two files need to be uploaded at the same time. And specify the file format and file size. Because the front-end framework uses angular, and I don’t want to introduce jquery for an upload function, I looked for upload controls based on angular on the Internet. Because angular is still relatively new, it seems that there are no mature plug-ins. Most of the online tutorials are copy and paste. , in short, it didn’t have much effect... But Huangtian paid off, and finally let me encounter this powerful plug-in, which made me feel like I was too late to meet you. With the help of official documents and senior brothers, I finally came across it. Understood the basic usage. Good things must be shared, so now I will share with you how to use it. If you happen to need to use it, I hope it can help you.

Upload button style
First of all, I want to talk about the button style for uploading files. Why? Everyone knows that this tag will be used for uploading. , the default style of this line of code is really a bit ugly, see the picture below:

In a website that is a little bit stylish, such a style really loses the image. And if you need to add an input box in front to display the file name, how can you hide the default area that displays the file name? ? Don’t worry, keep reading:

Wrap the input tag with an a tag, and then set the opacity of the input tag to 0, and that’s it! ok, look at the code:

html:

  <div>
    <input class="filename" type="text" readonly="readonly" />
    <a href="javascript:;" name="file">
      <input type="file" name="key"/>浏览
    </a>
  </div>
    <div>
    <input class="filename" type="text" readonly="readonly" />
    <a href="javascript:;" name="file">
      <input type="file" name="key"/>浏览
    </a>
  </div>
Copy after login

Then the css file:

.filename{
  width: 300px;
  height: 30px;
  line-height: 30px;
}
a{
  width: 50px;
  text-align: center;
  height: 30px;
  line-height: 30px;
  position: raletive;
  cursor: pointer;
  overflow:hidden;
  display: inline-block;
}
a input{
  position: absolute:
  left: 0;
  top: 0;
  opacity: 0;
}
Copy after login

You’re done! ! ! The style you see becomes like this, see the picture below:

You can control the front input box to display the file name you selected. Isn’t it much nicer?

angular-file-upload

The files we need can be found in the example. The es5-shim.min.js file in the example was introduced for compatibility with old browsers, so this plug-in is really powerful.

Then let’s use this plug-in step by step to implement the file upload function.

This plug-in defines several instructions: nv-file-drop, nv-file-select, uploader

Judging from the meaning of the words, it should not be difficult to guess. The first one supports file drag selection, and the second one is click selection. Uploader is used to bind the upload object newly created in the controller.

html file

<form class="form-horizontal" name="form">
  <div class="form-line">
    <label>请选择证书文件:</label><span class="small-tip">证书文件只支持.pem格式,文件大小1M以内</span>
    <div class="choose-file-area">
      <input class="file-name" type="text" readonly="readonly" ng-model="fileItem.name"/>
      <a href="javascript:;" class="choose-book">
        <input type="file" name="certificate" nv-file-select uploader="uploader" ng-click="clearItems()"/>浏览
      </a>
    </div>
  </div>
  <div class="form-line">
    <label>请选择私钥文件:</label><span class="small-tip">私钥文件只支持.key格式,文件大小1M以内</span>
    <div class="choose-file-area">
      <input class="file-name" type="text" readonly="readonly" ng-model="fileItem1.name"/>
      <a href="javascript:;" class="choose-key">
        <input type="file" name="key" nv-file-select uploader="uploader1" ng-click="clearItems1()"/>浏览
      </a>
    </div>
  </div>
  <button type="submit" ng-click="UploadFile()">提交</button>
</form>
Copy after login

First of all, note that two files need to be uploaded here, so I created two upload objects to facilitate file management and callback function processing. Finally, give the upload button a click event and handle the upload events of the two objects at the same time.

Controller file

var app = angular.module('app', ['angularFileUpload']);
app.controller('uploadController',['$scope', 'FileUploader', function($scope, FileUploader) {
  $scope.uploadStatus = $scope.uploadStatus1 = false; //定义两个上传后返回的状态,成功获失败
  var uploader = $scope.uploader = new FileUploader({
    url: 'upload.php',
    queueLimit: 1,   //文件个数 
    removeAfterUpload: true  //上传后删除文件
  });
  var uploader1 = $scope.uploader1 = new FileUploader({
    url: 'upload.php',
    queueLimit: 1,
    removeAfterUpload: true  
  });
  $scope.clearItems = function(){  //重新选择文件时,清空队列,达到覆盖文件的效果
    uploader.clearQueue();
  }
  $scope.clearItems1 = function(){
    uploader1.clearQueue();
  }
  uploader.onAfterAddingFile = function(fileItem) {
    $scope.fileItem = fileItem._file;  //添加文件之后,把文件信息赋给scope
  };
  uploader1.onAfterAddingFile = function(fileItem) {
    $scope.fileItem1 = fileItem._file;  //添加文件之后,把文件信息赋给scope
    //能够在这里判断添加的文件名后缀和文件大小是否满足需求。
  };
  uploader.onSuccessItem = function(fileItem, response, status, headers) {
    $scope.uploadStatus = true;  //上传成功则把状态改为true
  };
  uploader1.onSuccessItem = function(fileItem,response, status, headers){
    $scope.uploadStatus1 = true;
  }
  $scope.UploadFile = function(){
    uploader.uploadAll();
    uploader1.uploadAll();
    if(status){
      if(status1){
        alert('上传成功!');
      }else{
        alert('证书成功!私钥失败!');
      }
    }else{
      if(status1){
        alert('私钥成功!证书失败!');
      }else{
        alert('上传失败!');
      }
    }
  }
}])
Copy after login

Summary
In the above example, I defined two upload objects because I need to upload two files. Every time I reselect a file, I should overwrite the previously selected file. Therefore, if I define an object, it is a bit difficult to overwrite it. position, and define two objects, when reselecting, you can clear the file queue of the current object first, and then add it.

In fact, I later discovered that it is not necessary to define two upload objects, because this plug-in provides a removeFromQueue(index) method, and index is the index value of the file in the file queue array. Because the file is selected twice, the length is controlled to 2, and then this method is called each time it is selected, and 0 or 1 is passed in according to the position.

If you need to be able to select multiple files in the same window, just use .

If you need to limit the file type, you can use '.

Accept value type list:

* accept="application/msexcel"

* accept="application/msword"

* accept="application/pdf"

* accept="application/poscript"

* accept="application/rtf"

* accept="application/x-zip-compressed"
 
* accept="audio/basic"

* accept="audio/x-aiff"

* accept="audio/x-mpeg"

* accept="audio/x-pn/realaudio"

* accept="audio/x-waw"

* accept="image/*"

* accept="image/gif"
  
* accept="image/jpeg"

* accept="image/tiff"

* accept="image/x-ms-bmp"

* accept="image/x-photo-cd"

* accept="image/x-png"

* accept="image/x-portablebitmap"

* accept="image/x-portable-greymap"

* accept="image/x-portable-pixmap"

* accept="image/x-rgb"

* accept="text/html"

* accept="text/plain"

* accept="video/quicktime"

* accept="video/x-mpeg2"

* accept="video/x-msvideo"
Copy after login

This plug-in also provides a lot of configuration parameters, object methods and callback functions.

The above is an introduction to how to use the AngularJS file upload control. I hope it will be helpful to everyone's learning.

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)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

See all articles