6 Replies Latest reply on Jun 3, 2009 1:50 AM by twitskull

    Uploading files to server

    twitskull

      Hi,

       

      I would like to upload several files to server. I allready wrote my php file for accepting POST's. It works perfectly when I use Filereference and selecting file with browse option. I have event listeners for wathing when specific file is uploaded.

       

      private function startUpload(booIsFirst:Boolean):void
                  {
                      if (booIsFirst)
                      {
                          _numCurrentUpload = 0;
                      }
                      if (_arrUploadFiles.length > 0)
                      {
                          _winProgress = winProgress(PopUpManager.createPopUp(this, winProgress, true));
                          _winProgress.btnCancel.removeEventListener("click", onUploadCanceled);
                          _winProgress.btnCancel.addEventListener("click", onUploadCanceled);
                          _winProgress.title = "Uploading file to " + _strUploadDomain;
                          _winProgress.txtFile.text = _arrUploadFiles[_numCurrentUpload].label;
                          _winProgress.progBar.label = "0%";
                          PopUpManager.centerPopUp(_winProgress);
                         
                          // Variables to send along with upload
                          var sendVars:URLVariables = new URLVariables();
                          sendVars.action = "upload";
                          sendVars.credentials = tbxCredentials.text;
                         
                          var request:URLRequest = new URLRequest();
                          request.data = sendVars;
                          request.url = _strUploadScript;
                          request.method = URLRequestMethod.POST;
                          _refUploadFile = new FileReference();
                          _refUploadFile = _arrUploadFiles[_numCurrentUpload].data;
                        
                          _refUploadFile.addEventListener(ProgressEvent.PROGRESS, onUploadProgress);
                             _refUploadFile.addEventListener(Event.COMPLETE, onUploadComplete);
                          _refUploadFile.addEventListener(IOErrorEvent.IO_ERROR, onUploadIoError);
                            _refUploadFile.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onUploadSecurityError);
                          _refUploadFile.upload(request, "file", false);
                      }
                  }

       

      But now I need something different. I have local folder and in it some images that I need to upload to server. I wrote this function and it returns all files in that direcotry

       

      var imageDirectory:File = File.applicationStorageDirectory.resolvePath("yachtImages");
                      var x:String = "";
                      var dirContents:Array = imageDirectory.getDirectoryListing();
                      for(var i:int=0; i < dirContents.length; i++)
                      {
                          x += dirContents[i].name + " " + dirContents[i].size + " bytes\n";
                          _sumSize += dirContents[i].size;
                         
                          _aryImages.push({label: dirContents[i].name, data: "file://" + imageDirectory.nativePath.replace(/\\(\.*)/g, "/") + "/" + dirContents[i].name});
                         
                      }
                      lstImages.dataProvider = _aryImages;

       

       

      The problem is that I cannot figure out how to use it in my previous example. I just cant create FileReference instance for each file. Is there any easiest way to upload files with posting it to server and still having progress bar.

        • 1. Re: Uploading files to server
          Jeff Swartz Level 3

          You say "I just cant create FileReference instance for each file." The File class extends the FileReference class.

          1 person found this helpful
          • 2. Re: Uploading files to server
            twitskull Level 1

            Can you please show me snippet of a code. I am kinda lost here.

            • 3. Re: Uploading files to server
              Jeff Swartz Level 3

              I see. You want to get the data of the File (and the data property of a FileReference or File object is only set if you call the load() method).

               

              So for a file object, you want to do the following.

               

              var file:File; // set this to one of the files in the directory.

               

              var stream:FileStream = new FileStream();

              stream.open(file, FileMode.READ);

              var data:ByteArray = new ByteArray();
              stream.readBytes(data, 0, stream.bytesAvailable);
              stream.close();

              1 person found this helpful
              • 4. Re: Uploading files to server
                twitskull Level 1

                I am using it like this now

                 

                private function getImages():void
                            {
                                var imageDirectory:File = File.applicationStorageDirectory.resolvePath("yachtImages");
                                var dirContents:Array = imageDirectory.getDirectoryListing();
                                for(var i:int=0; i < dirContents.length; i++)
                                {
                                    _sumSize += dirContents[i].size;   
                                    _aryImages.push({label: dirContents[i].name, data: "file://" + imageDirectory.nativePath.replace(/\\(\.*)/g, "/") + "/" + dirContents[i].name});
                                   
                                }
                                lstImages.dataProvider = _aryImages;
                               
                                for each (var item:Object in _aryImages)
                                {
                                   
                                   
                                    var file:File = File.applicationStorageDirectory.resolvePath("yachtImages/" + item.label);
                                    
                                   
                                    var stream:FileStream = new FileStream();
                                    stream.open(file, FileMode.READ);
                                    var data:ByteArray = new ByteArray();
                                    stream.readBytes(data, 0, stream.bytesAvailable);
                                    stream.close();
                                   
                                    var fileref:FileReference = new FileReference();
                                    fileref = file as FileReference;
                                    //fileref = data;

                                   
                                    trace(item.label);
                                }
                               
                            }

                 

                 

                I dont know if I can use it now for uploading via URLRequest? What do I do with data bytearray and what i accomplishe with stream reading? Please a little bit help more

                • 5. Re: Uploading files to server
                  Jeff Swartz Level 3

                  There's no need to even reference the ByteArray data. So you can ignore what I said about reading data via a FileStream object. (Sorry for the confusion.)

                   

                  Simply call the upload() method of each File object. (The File class extends the FileReference class, so File objects have an upload() method).

                   

                  For example:

                   

                  var sendVars:URLVariables = new URLVariables();
                  sendVars.action = "upload";
                  sendVars.credentials = "foo";
                    
                  var request:URLRequest = new URLRequest();
                  request.data = sendVars;
                  request.method = URLRequestMethod.POST;
                  request.url = "http://localhost/foo";

                   

                  var files:Array = File.documentsDirectory.resolvePath("test").getDirectoryListing();
                  var file:File;
                  for (var i:uint; i < files.length; i++)
                  {
                      file = files[i];
                      if (!file.isDirectory)
                      {
                          file.upload(request);
                          file.addEventListener(Event.COMPLETE, loaded);
                      }
                  }

                   

                  function loaded(event:Event):void
                  {
                      var file:File = event.target as File;
                      trace(file.name, "uploaded.");
                  }

                  • 6. Re: Uploading files to server
                    twitskull Level 1

                    Jeff, thanks for all the help. With your help I solved it now

                     

                    private function init():void
                    {
                        sqlConnection = new SQLConnection();
                        sqlConnection.open(dbFile);
                        sqlStat = new SQLStatement();
                        sqlStat.sqlConnection = sqlConnection;
                       
                        var connection = new LocalConnection();
                        connection.allowDomain("*");
                        connection.client = this;
                        connection.connect("_myconnect");
                       
                        loadImages();
                    }

                     

                    private var aryImages:Array = new Array();
                    private var intCurrentImageIndex:Number;
                    private var popWinProgress:winProgress;
                    private var currentLocalImage:File;

                     

                    private function loadImages():void
                    {
                        var directoryImages:Array = File.applicationStorageDirectory.resolvePath("yachtImages").getDirectoryListing();
                        var currentImageFile:File;
                        var intUploadSize:Number = 0;
                       
                        for (var i:uint; i < directoryImages.length; i++)
                        {
                            currentImageFile = directoryImages[i];
                            if (!currentImageFile.isDirectory)
                            {
                                aryImages.push(currentImageFile.name);
                                intUploadSize += currentImageFile.size;
                            }
                        }
                       
                        intUploadSize = int(((intUploadSize / 1024) / 1024) * 100) / 100;
                        lblFilesTotal.text = String(aryImages.length);
                        lblUploadSize.text = String(intUploadSize) + " MB";
                        btnSynchronize.enabled = true;
                    }

                     

                    private function uploadToServer(isFirstElement:Boolean):void
                    {
                        if (isFirstElement)
                        {
                            intCurrentImageIndex = 0;
                        }
                       
                        if (aryImages.length > 0)
                        {
                            popWinProgress = winProgress(PopUpManager.createPopUp(this, winProgress, true));
                            popWinProgress.btnCancel.removeEventListener("click", onSyncCanceled);
                            popWinProgress.btnCancel.addEventListener("click", onSyncCanceled);
                            popWinProgress.title = "Uploading file to " + tbxServer.text;
                            popWinProgress.txtFile.text = aryImages[intCurrentImageIndex] + " [" + String(intCurrentImageIndex + 1) + " of " + String(aryImages.length) + "]";
                            popWinProgress.progBar.label = "0%";
                            PopUpManager.centerPopUp(popWinProgress);
                           
                            var sendVars:URLVariables = new URLVariables();
                            sendVars.action = "upload";
                            sendVars.credentials = tbxCredentials.text;
                           
                            var request:URLRequest = new URLRequest();
                            request.data = sendVars;
                            request.url = tbxServer.text + ":" + tbxPort.text + "/" + tbxService.text + "/";
                            request.method = URLRequestMethod.POST;
                           
                            currentLocalImage = File.applicationStorageDirectory.resolvePath("yachtImages/" + aryImages[intCurrentImageIndex]);
                            currentLocalImage.addEventListener(ProgressEvent.PROGRESS, onSyncProgress);
                            currentLocalImage.addEventListener(Event.COMPLETE, onSyncComplete);
                            currentLocalImage.addEventListener(IOErrorEvent.IO_ERROR, onSyncIOError);
                            currentLocalImage.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSyncSecurityError);
                            currentLocalImage.upload(request, "file", false);
                        }
                       
                    }

                     

                    private function onSyncCanceled(event:Event):void
                    {
                        PopUpManager.removePopUp(popWinProgress);
                        popWinProgress == null;
                        currentLocalImage.cancel();
                        clearSync();
                    }

                     

                    private function onSyncProgress(event:ProgressEvent):void
                    {
                        var intPercent:Number = Math.round((Number(event.bytesLoaded) / Number(event.bytesTotal)) * 100);
                        popWinProgress.progBar.setProgress(intPercent, 100);
                        popWinProgress.progBar.label = intPercent + "%";
                        popWinProgress.progBar.validateNow();
                        if (intPercent > 90)
                        {
                            popWinProgress.btnCancel.enabled = false;
                        }
                        else
                        {
                            popWinProgress.btnCancel.enabled = true;
                        }
                       
                    }

                     

                    private function onSyncComplete(event:Event):void
                    {
                        intCurrentImageIndex++;
                        PopUpManager.removePopUp(popWinProgress);
                        if (intCurrentImageIndex < aryImages.length)
                        {
                            uploadToServer(false);
                            progressAll.setProgress(intCurrentImageIndex + 1, aryImages.length);
                        }
                        else
                        {
                            Alert.show("File(s) have been uploaded.", "Synchronization completed");
                        }
                    }

                     

                    private function onSyncIOError(event:IOErrorEvent):void
                    {
                        Alert.show("IO Error in uploading file.", "Error");
                        PopUpManager.removePopUp(popWinProgress);
                        popWinProgress == null;
                        currentLocalImage.cancel();
                        clearSync();
                    }
                               
                    private function onSyncSecurityError(event:SecurityErrorEvent):void
                    {
                        Alert.show("Security Error in uploading file.", "Error");
                        PopUpManager.removePopUp(popWinProgress);
                        popWinProgress == null;
                        currentLocalImage.cancel();
                        clearSync();
                    }

                     

                    private function clearSync():void
                    {
                        intCurrentImageIndex = 0;
                        currentLocalImage.removeEventListener(ProgressEvent.PROGRESS, onSyncProgress);
                        currentLocalImage.removeEventListener(Event.COMPLETE, onSyncComplete);
                        currentLocalImage.removeEventListener(IOErrorEvent.IO_ERROR, onSyncIOError);
                        currentLocalImage.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, onSyncSecurityError);
                        currentLocalImage.cancel();
                    }