6 Replies Latest reply on Oct 2, 2009 10:47 AM by David_F57

    multiple file loader, saves 101 copies of image on server... need help :)

    cyber0897 Level 1

      hey guys, like the title suggests... for some reason my actionscript file saves the stupid image 101 times on the server... and thats only cuz i stop the script from running more... lol

       

      the code i have is...

       

          public var fileRef:FileReferenceList = new FileReferenceList();
          [Bindable] public var fileList:Array = new Array();
          [Bindable] public var fileNames:ArrayCollection = new ArrayCollection();
          [Bindable] public var arrUploadFiles:Array = new Array();
          public var file:FileReference;
         
         
          public var imageData:ImageData = new ImageData();
          public var imageService:Images = new Images();
          public var returnMsg:ReturnMessage = new ReturnMessage();
         
          public function initiateBrowse():void{
              var filter:Array = [];
              filter.push(new FileFilter("Images", ".gif;*.jepg;*.jpg;*.png"));
              this.fileRef.addEventListener(Event.SELECT, addToQueue);
              this.fileRef.browse(filter);
          }
          public function addToQueue(event:Event):void{
              // (event.target.fileList.length);
              var numSelected:Number = event.target.fileList.length;
              for(var i:int; i < numSelected; i++){
                  var oldListLength:Number = fileList.length;
                  fileList.push(event.target.fileList[i]);
                  fileNames.addItem({
                      num: fileNames.length + 1,
                      name: event.target.fileList[i].name,
                      size: formatFileSize(event.target.fileList[i].size),
                      status:""
                  });
                  var newListLength:Number = fileList.length;
                 
                  if(oldListLength < newListLength){
                      uploadToServer(oldListLength, event);
                  }
              }
          }
         
          private function uploadToServer(startIndex:Number, event:Event):void{
              var files:FileReferenceList = FileReferenceList(event.target);
              trace("file list length: " + fileList.length);
              for(var i:int = startIndex; i < fileList.length; i++){
                  file = new FileReference();
                  file = FileReference(fileList[i]);
                  file.addEventListener(Event.COMPLETE, uploadSingleFile);
                  file.load();
              }
          }
         
          private function uploadSingleFile(event:Event):void{
              var fileByteArr:ByteArray = event.target.data as ByteArray;
              var b64En:Base64Encoder = new Base64Encoder();
              b64En.encodeBytes(fileByteArr);
             
              var str:String = b64En.flush();
              //trace(str);
              imageData.Base64EncodedImage = str;
              imageData.FileName = event.target.name
              Alert.show(event.target.name);
              imageService.addEventListener(ResultEvent.RESULT, imgServSuccess);
              imageService.UploadImage(imageData);
              b64En.reset();
          }
         
          public function imgServSuccess(event:ResultEvent):void{
              var returnedImageId:ArrayCollection = new ArrayCollection();
              returnMsg = event.result as ReturnMessage;
              var returnedData:Object = event.result.Images;
              trace("length: " + event.result.Images.length);
             
              if(returnMsg.ThereWasAnError){
                  trace(returnMsg.ErrorMessages.getItemAt(0).toString());
              }
              else{
                  for each(var imgData:ImageData in returnedData){
                      var decoded:Base64Decoder = new Base64Decoder();
                      decoded.decode(imgData.Base64EncodedImage);
                      var byteArr:ByteArray = decoded.toByteArray();
                      img.source = byteArr;
                  }
                  imageService.SaveUploadedImageInformation(returnedData[0]);
                  trace("done");
              }
          }

       

          private function formatFileSize(numSize:Number):String {
                      var strReturn:String;
                      numSize = Number(numSize / 1024);
                      strReturn = String(numSize.toFixed(1) + " KB");
                      if (numSize > 1024) {
                          numSize = numSize / 1024;
                          strReturn = String(numSize.toFixed(1) + " MB");
                          if (numSize > 1024) {
                              numSize = numSize / 1024;
                              strReturn = String(numSize.toFixed(1) + " GB");
                          }
                      }               
                      return strReturn;
         }

       

      and in the mxml i have

       

          <s:VGroup>
              <mx:DataGrid id="displayFilesList" width="700" height="500" allowMultipleSelection="true" resizableColumns="true" draggableColumns="false" dataProvider="{fileNames}">
                  <mx:columns>
                      <mx:DataGridColumn headerText="#" dataField="num" width="30" />
                      <mx:DataGridColumn headerText="File" dataField="name" width="400"/>
                      <mx:DataGridColumn headerText="Size" dataField="size" width="75" textAlign="right" />
                      <mx:DataGridColumn headerText="Status" dataField="status">
                         
                      </mx:DataGridColumn>
                  </mx:columns>
              </mx:DataGrid>

       

              <s:Button label="Browse" click="initiateBrowse();" />
              <mx:Image id="img" width="700" height="300" />
          </s:VGroup>

       

       

       

      can any one point out what my problem is?? ive been wracking my brains over this stupid issue like all day! lol

      if you would like some more information on the data service please let me know i can take an image of the data service and post it up...

       

      again thank you soo much in advance!!!

        • 1. Re: multiple file loader, saves 101 copies of image on server... need help :)
          David_F57 Level 5

          Hi,

           

          I have found that if you are just wanting to upload a group of files it isn't a good idea to "queue" them. Instead I would declare a counter and use the load complete event to fire the next item.(also this makes it easier to have a cancel routine)

           

          i.e.

           

          private var myCounter:int = 0;

           

          private function selectedImages(e:Event): void

          {

          filelist.removeEventListener(Event.SELECT, selectedImages);

          loopList(0);

          }

           

           

          private function loopList(value:int): void

          {

          if (value < filelist.length)

          {

          file = filelist.fileList[value];

          file.addEventListener(Event.COMPLETE,loadImage);

          file.load();

          }

           

          }

           

          private function loadImage(e:Event): void

          {

          file.removeEventListener(Event.COMPLETE, getImage);

          myCounter += 1;

          if (myCounter < filelist.length) LoopList(MyCounter);

          }

           

          Anyway thats my thoughts, there are some 3rd party components for uploading images but I haven't really looked at them so I couldn't suggest how good/bad they are.

           

           

          David.

          1 person found this helpful
          • 2. Re: multiple file loader, saves 101 copies of image on server... need help :)
            mewk Level 3

            Hey cyber,

             

            While I agree with David that I might not have programmed your image uploader in exactly this way (there are some questionable moves here and there!! ), I didn't see anything wrong with the code to make me think it shouldn't work. In fact, I ran your code, with dummy classes to fill the gaps, and all I got was successful results (no infinite loops).

             

            I suspect that if there is a problem with your code it can be found in either ImageS::UploadImage() or ImageS::SaveUploadedImageInformation(). If you need more input it would help if you would supply the missing classes (ImageData; ImageS, ReturnMessage). Good luck!

             

            - e

            • 3. Re: multiple file loader, saves 101 copies of image on server... need help :)
              cyber0897 Level 1

              hey guys, thank you sooo much for getting back to me soo fast!! i really appretiate it!!


              i changed up my code to have the counter in there... and it seems to have fixed the problem.... but unfortunately i dont get all the images uploaded

              its weird, it uploads only a select amount of images... and it seems to be random..

              my last 2 tries, it didnt up load any images...

              not sure where the problem is... any more suggestions would be greatly appretiated!!!

               

              here is the updated code

               

              import flash.events.Event;
              import flash.net.FileReference;
              import flash.net.FileReferenceList;
              import flash.utils.ByteArray;

               

              import mx.collections.ArrayCollection;
              import mx.controls.Alert;
              import mx.rpc.events.ResultEvent;
              import mx.utils.Base64Decoder;
              import mx.utils.Base64Encoder;

               

              import services.images.ImageData;
              import services.images.Images;
              import services.images.ReturnMessage;

               

                  public var t:Number = 0;

               

                  public var fileRef:FileReferenceList = new FileReferenceList();
                  [Bindable] public var fileList:Array = new Array();
                  [Bindable] public var fileNames:ArrayCollection = new ArrayCollection();
                  [Bindable] public var arrUploadFiles:Array = new Array();
                  public var file:FileReference;
                 
                 
                  public var imageData:ImageData = new ImageData();
                  public var imageService:Images = new Images();
                  public var returnMsg:ReturnMessage = new ReturnMessage();
                 
                  public var myCounter:int = 0;
                 
                 
                  public function initiateBrowse():void{
                      var filter:Array = [];
                      filter.push(new FileFilter("Images", ".gif;*.jepg;*.jpg;*.png"));
                      this.fileRef.addEventListener(Event.SELECT, selectedImages);
                      this.fileRef.browse(filter);
                  }
                 
                  public function selectedImages(event:Event):void{
                      fileRef.removeEventListener(Event.SELECT, selectedImages);

               

                      var numSelected:Number = event.target.fileList.length;
                      for(var i:int; i < numSelected; i++){
                          var oldListLength:Number = fileList.length;
                          fileList.push(event.target.fileList[i]);
                          fileNames.addItem({
                              num: fileNames.length + 1,
                              name: event.target.fileList[i].name,
                              size: formatFileSize(event.target.fileList[i].size),
                              status:""
                          });
                          var newListLength:Number = fileList.length;       
                      }
                      loopList(0);
                  }
                 
                  public function loopList(value:int):void{
                      if(value < fileList.length){
                          file = new FileReference();
                          file = FileReference(fileList[value]);;
                          trace("---------------> starting to upload " + file.name);
                          file.addEventListener(Event.COMPLETE, loadImage);
                          file.load();
                      }
                  }
                 
                  public function loadImage(event:Event):void{
                      file.removeEventListener(Event.COMPLETE, loadImage);
                      trace("my counter: " + myCounter + "  my fileList length is: " + fileList.length);
                      myCounter += 1;
                      if(myCounter <= fileList.length){
                         
                          var fileByteArr:ByteArray = event.target.data;
                          var b64En:Base64Encoder = new Base64Encoder();
                          b64En.encodeBytes(fileByteArr);
                         
                          var str:String = b64En.flush();
                          //trace(str);
                          imageData.Base64EncodedImage = str;
                          imageData.FileName = event.target.name
                          imageService.addEventListener(ResultEvent.RESULT, imgServSuccess);
                          imageService.UploadImage(imageData);
                          b64En.reset();
                     
                          loopList(myCounter);
                         
                      }
                  }

               

                  public function imgServSuccess(event:ResultEvent):void{
                      imageService.removeEventListener(ResultEvent.RESULT, imgServSuccess);
                      var returnedImageId:ArrayCollection = new ArrayCollection();
                      returnMsg = event.result as ReturnMessage;
                      var returnedData:Object = event.result.Images;
                     
                      var imgD:ImageData = new ImageData();
                     
                      if(returnMsg.ThereWasAnError){
                          trace(returnMsg.ErrorMessages.getItemAt(0).toString());
                      }
                      else{
                          for each(var imgData:ImageData in returnedData){
                              var decoded:Base64Decoder = new Base64Decoder();
                              decoded.decode(imgData.Base64EncodedImage);
                              var byteArr:ByteArray = decoded.toByteArray();
                              img.source = byteArr;
                              trace("<--------------- completed uploading " + imgData.FileName);
                          }
                          imageService.SaveUploadedImageInformation(returnedData[0]);
                          trace("done");
                      }
                  }
                 

                  private function formatFileSize(numSize:Number):String {
                              var strReturn:String;
                              numSize = Number(numSize / 1024);
                              strReturn = String(numSize.toFixed(1) + " KB");
                              if (numSize > 1024) {
                                  numSize = numSize / 1024;
                                  strReturn = String(numSize.toFixed(1) + " MB");
                                  if (numSize > 1024) {
                                      numSize = numSize / 1024;
                                      strReturn = String(numSize.toFixed(1) + " GB");
                                  }
                              }               
                              return strReturn;
                 }

              • 4. Re: multiple file loader, saves 101 copies of image on server... need help :)
                David_F57 Level 5

                Ok, that was probably my fault as I only gave you the basic idea of avoiding the queueing, once you have loaded the image from the hard disk you should then jump to your upload data routine, after your upload suceeds set your counter and loop back for the next file. After a lot of experimentation(up to 500 images per upload) I found forcing the whole process into a very sequential loop always gave more reliable results for only a small loss in time.

                 

                Also I am not sure why you are looping through the fileref initially unless you are creating an array for some other purpose. There is no reason to do this as the values you pass from fileref could just as easily be done in the looplist procedure which is a little more efficient than iterating through the fileref list twice.

                 

                Personally I prefer to use remote objects for image transfer, as you bypass the need to string encode the binary file which is much faster and cleaner.

                 

                David

                • 5. Re: multiple file loader, saves 101 copies of image on server... need help :)
                  cyber0897 Level 1

                  hey david... thank you again for the suggestion!!! i was able to implement similar idea in my application lol

                  it works like a champ now...

                  this is the code i ended up with.... just thought u might like to see the end result

                   


                      public var t:Number = 0;

                      public var fileRef:FileReferenceList = new FileReferenceList();
                      [Bindable] public var fileListArr:Array = new Array();
                      [Bindable] public var fileNames:ArrayCollection = new ArrayCollection();
                      [Bindable] public var arrUploadFiles:Array = new Array();
                      public var file:FileReference;
                     
                     
                      public var imageData:ImageData;
                      public var imageService:Images = new Images();
                      public var saveImages:Images = new Images();
                      public var returnMsg:ReturnMessage = new ReturnMessage();
                     
                      public var myCounter:int = 0;
                      public var numPerc:Number;
                     
                      public function initiateBrowse():void{
                          var filter:Array = [];
                          filter.push(new FileFilter("Images", ".gif;*.jepg;*.jpg;*.png"));
                          fileRef.addEventListener(Event.SELECT, selectionHandler);
                          fileRef.browse(filter);
                      }
                     
                      public function selectionHandler(event:Event):void{
                          fileRef.removeEventListener(Event.SELECT, selectionHandler);
                          //fileList.push(event.target.fileList);
                          var numSelected:int = event.target.fileList.length;
                          var fileList:Array = event.target.fileList;
                          //trace("numSelected " + numSelected);
                          //fileListArr = fileRef.fileList;
                          //var oldListLength:Number = fileListArr.length;
                          for each(var item:Object in fileList){
                              fileListArr.push(item);
                              fileNames.addItem({
                                  num: fileNames.length + 1,
                                  name: item.name,
                                  size: formatFileSize(item.size),
                                  status: ""
                              });
                          }
                          var newListLength:Number = fileListArr.length;   
                          loopList(0);
                      }
                     
                     
                      public function loopList(value:int):void{
                          //trace("Value: " + value + "  file list array: " + fileListArr.length);
                          if(value < fileListArr.length){
                              file = new FileReference();
                              file = FileReference(fileListArr[value]);;
                              //trace("---------------> starting to upload " + file.name);
                              file.addEventListener(Event.COMPLETE, loadImage);
                              file.addEventListener(ProgressEvent.PROGRESS, fileProgress);
                              file.load();
                          }
                      }
                     
                      public function loadImage(event:Event):void{
                          file.removeEventListener(Event.COMPLETE, loadImage);
                          //trace("my counter: " + myCounter + "  my fileList length is: " + fileListArr.length);
                              myCounter += 1;
                              var fileByteArr:ByteArray = event.target.data;
                              var b64En:Base64Encoder = new Base64Encoder();
                              b64En.encodeBytes(fileByteArr);
                             
                              var str:String = b64En.flush();
                              //trace(str);
                              imageData = new ImageData();
                              imageData.Base64EncodedImage = str;
                              imageData.FileName = event.target.name;
                              trace("sending -->>  " + imageData.FileName);
                              imageService.addEventListener(ResultEvent.RESULT, imgServSuccess);
                              imageService.UploadImage(imageData);
                              b64En.reset();
                      }

                      public function imgServSuccess(event:ResultEvent):void{
                          imageService.removeEventListener(ResultEvent.RESULT, imgServSuccess);
                          var returnedImageId:ArrayCollection = new ArrayCollection();
                          returnMsg = event.result as ReturnMessage;
                          var returnedData:Object = event.result.Images;
                          trace("getting back -->> " + returnedData[0].FileName);
                          var imgD:ImageData = new ImageData();
                         
                          if(returnMsg.ThereWasAnError){
                              trace(returnMsg.ErrorMessages.getItemAt(0).toString());
                          }
                          else{
                              for each(var imgData:ImageData in returnedData){
                                  var decoded:Base64Decoder = new Base64Decoder();
                                  decoded.decode(imgData.Base64EncodedImage);
                                  var byteArr:ByteArray = decoded.toByteArray();
                                  img.source = byteArr;
                                  //trace("<--------------- completed uploading " + imgData.FileName);
                              }
                              saveImages.addEventListener(ResultEvent.RESULT, savedSuccess);
                              saveImages.SaveUploadedImageInformation(returnedData[0]);
                              //trace("done");
                          }
                      }
                     
                      public function savedSuccess(event:ResultEvent):void{
                          var retMsg:Object = event.result.Images;
                          trace("saving -->> " + retMsg[0].FileName);
                          loopList(myCounter);
                      }

                      public function fileProgress(event:ProgressEvent):void{
                          var numPerc:Number = Math.round((Number(event.bytesLoaded) / Number(event.bytesTotal)) * 100);
                          //trace(numPerc);
                      }

                      private function formatFileSize(numSize:Number):String {
                          var strReturn:String;
                          numSize = Number(numSize / 1024);
                          strReturn = String(numSize.toFixed(1) + " KB");
                          if (numSize > 1024) {
                              numSize = numSize / 1024;
                              strReturn = String(numSize.toFixed(1) + " MB");
                              if (numSize > 1024) {
                                  numSize = numSize / 1024;
                                  strReturn = String(numSize.toFixed(1) + " GB");
                              }
                          }               
                          return strReturn;
                     }

                  • 6. Re: multiple file loader, saves 101 copies of image on server... need help :)
                    David_F57 Level 5

                    hi,

                     

                    Once you do this sort of thing a few times you will find your own preferences and ways of making things efficient, i'm glad I could help get you up and running.

                     

                    David