AngularJS implements Image Upload and preview functions,
This article describes how AngularJS implements Image Upload and preview functions. We will share this with you for your reference. The details are as follows:
Html5 NATIVE METHOD
Let's take a look at the implementation of the html5 native method for uploading and previewing images:
// var imgPreview = document. getElementById ("img-preview"); // <input id = "img-input" type = "file"> var imgInput = document. getElementById ("img-input"); imgInput. addEventListener ("change", function (e) {var imgFile = e.tar get. files [0]; // obtain the uploaded image var reader = new FileReader (); reader. readAsDataURL (imgFile); // convert the image to dataUri reader. onload = function (e) {imgPreview. src = e.tar get. result; // update image link }});
We can see that the onchange event is needed to obtain the uploaded file. When angularjs is used in the project, we naturally think of the ng-change command, but unfortunately, in angularjs, <input type = "file"> the ng-model and ng-change commands (Appendix 1) are not supported, which makes file Upload complicated.
Angularjs Method
Here, the open-source angular-file-upload module is used for implementation. The steps are as follows:
1. Install the angular-file-upload Module
bower install angular-file-upload --save
2. Add to application dependency
var app = angular.module('my-app', [ 'angularFileUpload']);
3. HTML code
<! -- File Upload Command --> <input type = "file" nv-file-select = "" uploader = "uploader"/> <! -- Image preview -->
In this example, nv-file-select = "" indicates uploading using the file selection method of the angular-file-upload module. For more information, see the official example.
4. controller code
. Controller ('appcontroller', ['$ scope', 'fileupload', function ($ scope, FileUploader) {var uploader = $ scope. uploader = new FileUploader ({url: 'upload. php '// change to your own upload address, and the local demo will not change.}); uploader. onAfterAddingFile = function (fileItem) {var reader = new FileReader (); reader. addEventListener ("load", function (e) {// After the file is loaded, update angular binding $ scope. $ apply (function () {$ scope. iconUrl = e.tar get. result;}) ;}, false); reader. readAsDataURL (fileItem. _ file) ;};}]);
As you can see, we can use the onAfterAddingFile callback function to obtain the selected image file, convert the image file to datauri, and then update the src attribute of the label.
It is worth noting that we put the "update the src attribute of the label" task to $ scope. run the $ apply method. This is because angular does not synchronously update the bound data outside the angular framework (for example, in a browser DOM Event, setTimeout, XHR, or a third-party framework. For more information, see angular $ apply reference.