How to integrate progress bar into angularjs directive with file upload

I need to create a progress bar to download files. I know that my progress event listener is working. Is there a more β€œangular way” for this? How to update progress bar inside my event listener?

As a preface, please feel free to correct and criticize the overall logical flow if it also needs help.

I have this canvas ...

<canvas id="progress"></canvas> 

I have an angularjs directive that uploads files. I added a listener to the progress events (only showing the relevant parts) ...

 link: function postLink(scope, element, attrs, ctrl) { var fileUpload = function (img, file) { var xhr = new XMLHttpRequest(); xhr.upload.addEventListener("progress", function(e) { if (e.lengthComputable) { var percentage = Math.round((e.loaded * 100) / e.total); // UPDATE THE PROGRESS BAR HERE } }, false); } element.bind('change', function (evt) { var files = evt.target.files; var canvas = document.getElementById("progress"), context = canvas.getContext("2d"); context.fillStyle = 'lighgray'; context.fillRect(0, 0, 200, 18); context.moveTo(0, 0); context.fillStyle = 'darkgray'; context.fillRect(0, 0, 1, 18); for(var i = 0; i < files.length; i++) { fileUpload(files, files[i]); } } } 
+4
source share
2 answers

Take a look at Angular UI Bootstrap: http://angular-ui.imtqy.com/bootstrap/

It provides directives for Bootstrap user interface elements, including a progress bar.

It looks like you just need to associate the download progress value with the panel and it will automatically update.

(Must love two-way data binding.)

+6
source

look at the HTML5 progress tag , your code will look like

  if (e.lengthComputable) { var percentage = Math.round((e.loaded * 100) / e.total); $('progress').val(percentage); } 

I know that it has a lot of compatibility issues and it looks different in different browsers (although you can fix it with css3: a good example )

in your case you have to fill the rectangle again and again

 if (e.lengthComputable) { var percentage = e.loaded / e.total; context.fillRect(0, 0, progressWidth*percentage, 18); } 

I got rid of *100% because you better use var progressWidth = 200 when creating the context

Check out this example , it shows better what I mean (and sorry for my English)

0
source

Source: https://habr.com/ru/post/1493338/


All Articles