简体   繁体   中英

AngularJS one file at a time upload

I am working on a AngularJS file upload controller. In this case the user should be able to upload a JPG containing all EXIF information in the file.

However, these are big (5mb+) jpg's send to a remote API. To prevent the server going down from 100+ file uploads (which is not unlikely) I want all the uploads to happen synchronously.

I am using the following ng-upload lib which states this fiddle uploads synchronously: https://jsfiddle.net/danialfarid/2vq88rfs/136/

However, when I run it with 5 files, they all get uploaded at once and I don't know how to change it so that the forEach uploads (see code example) the next file after the previous file has been uploaded.

angular.forEach(files, function(file) {
        file.upload = Upload.upload({
            url: 'https://angular-file-upload-cors-srv.appspot.com/upload',
            data: {file: file}
        });

Can someone tell me how this can be done synchronously?

All you have to do is create a queue that control sending request

step 1: create a variable to control the execution

this.indexFile = undefined;

step 2: Register a $watch to watch this.indexFile

   _attachListener() {
        let vm = this;
        vm._scope.$watch('vm.indexFile', function (newValue, oldValue) {
            if(newValue !== oldValue){
                vm._attachFile();
            }
        });
    }

step 3: code to send files

_attachFile(){
    if(this.indexFile < this.files.length){
        if (!this.files[this.indexFile].progress) {
              this.service.attach(this.files[this.indexFile])
                .then()
                .catch()
                .finally(()=>{
                    this.files[this.indexFile].progress = 100;
                    this.indexFile++ ;
              });
         }else{
            this.indexFile++ ;
         }
    }
}

step 4: start variable to control the execution

startIndexFile() {
    let vm = this;
    vm.indexFile = 0;
}

setp 5: html code to start the upload

<button type="button" ng-click="vm.startIndexFile()"></button>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM