3 Replies Latest reply on Nov 18, 2009 8:39 PM by flairjax

    byte array to base64encoder problem, cannot encode a 7.7 MB file

    cyber0897 Level 1

      hey guys, so ive been trying to use the base64encoder to encode a bytearray which is then sent thru a webservice to the server to be decoded.

       

      and as the subject of this post suggests, i have been having problems encoding a big file,

       

      forexample i tried to upload/convert a 84KB image and it worked just fine... the trace of the string ended with a "==" which i believe means that the conversion is complete...

       

      but when i try to upload a 7.7MB image, it is, i guess, crashing... i dont see any "==" in the string... so i guess its not working... i was wondering if there is any any type of file size limit or soemthign for the encoding...

       

      the code i have is

       

       

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

       

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

       

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

       

      // ActionScript file
          public var fileRef:FileReference = new FileReference();
         
          public var imgCollection:ArrayCollection = new ArrayCollection();
          public var imgService:Images = new Images();
          public var imageData:ImageData = new ImageData();
          public var returnMsg:ReturnMessage = new ReturnMessage();

       

          public function onBrowseButtonClicked(event:MouseEvent):void{
              var arr:Array = [];
              arr.push(new FileFilter("Images", ".gif;*.jepg;*.jpg;*.png"));
              fileRef.browse(arr);
              fileRef.addEventListener(Event.SELECT, fileRef_select);
              fileRef.addEventListener(Event.COMPLETE, fileRef_complete);
          }
         
          public function fileRef_select(event:Event):void{
              fileRef.load();
          }
         
          public function fileRef_complete(event:Event):void{
              img.source = fileRef.data;
             
              var fileByteArr:ByteArray = fileRef.data;
              var b64En:Base64Encoder = new Base64Encoder();
              b64En.encodeBytes(fileByteArr);                                                  //<----------------------------------------------------------

       

              var str:String = b64En.flush();                                                        //<----------------------------------------------------------
              trace(str.length);
              b64En.reset();
              trace("------------------------------------      " + str + "     -----------------------------");
              imageData.Base64EncodedImage = str;
              imageData.FileName = "nameofstring";
              imgService.UploadImage(imageData);

             imgService.addEventListener(FaultEvent.FAULT, servFault);
             imgService.addEventListener(ResultEvent.RESULT, imgServSuccess);
          }
         
          public function imgServSuccess(event:ResultEvent):void{
              Alert.show("i am in the result");
              returnMsg = event.result as ReturnMessage;
              var resultStr:String = event.result as String;
              Alert.show(resultStr);
             
              if(returnMsg.ThereWasAnError){
                  trace(returnMsg.ErrorMessages.getItemAt(0).toString());
              }

       

          }
         
          public function servFault(event:FaultEvent):void{
              Alert.show("2 " + event.fault.message);
              Alert.show("3 " + event.fault.faultCode);
          }

       

       

      any help will be greatly appretiated!! thanks in advace!

        • 1. Re: byte array to base64encoder problem, cannot encode a 7.7 MB file
          flairjax Level 1

          Having the same issue, did you figure this out?


          • 2. Re: byte array to base64encoder problem, cannot encode a 7.7 MB file
            cyber0897 Level 1

            yeah i did actually... except i think i changed a LOT of code since i last posted this article...

            so i dont remember where this code is exactly... lol

            i have the following code now...

            hope this helps

            i use a a lot of webservices... so there is some of that code included in there aswell...

             

             

            /***************************************************************************************** ******************************
            * This file will do the file upload. It has been suggested to me multiple times, that using a queueing system for
            * file upload is not a good idea. Instead I declared a counter and used the final function to fire the next item
            * in the array. this also makes canceling a routine easier.
            ****************************************************************************************** *****************************/

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

            import mx.collections.ArrayCollection;
            import mx.controls.*;
            import mx.managers.*;
            import mx.rpc.events.FaultEvent;
            import mx.rpc.events.ResultEvent;
            import mx.utils.Base64Decoder;
            import mx.utils.Base64Encoder;

            import services.images.Images;

            import valueObjects.*;

                public var t:Number = 0;

                public var fileRef:FileReferenceList = new FileReferenceList();
                public var listCacheFiles:Array = new Array();
                [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 _numCurrentUpload:Number = 0;
                public var imageData:valueObjects.ImageData;
                public var imageService:Images = new Images();
                public var saveImages:Images;
                public var returnMsg:ReturnMessage = new ReturnMessage();
               
                public var dataToSave:ImageData;
               
                public var myCounter:int = 0;
                public var numPerc:Number;
               
                /*vars to possible delete*/
                public var fileListx:ArrayCollection;
               
                /**************************************************************************************** *************************
                 * Initiates the browse, when files are selected the selectionHandler function is called
                ***************************************************************************************** ************************/
                public function initiateBrowse():void{
                    var filter:Array = [];
                    filter.push(new FileFilter("Images", ".gif;*.jepg;*.jpg;*.png"));
                    fileRef.addEventListener(Event.SELECT, selectionHandler);
                    fileRef.browse(filter);
                }
               
                /**************************************************************************************** *************************
                 * selection handler takes the selected files and puts them in 2 different arrays
                 * fileListArr contains all the file information like the image itself and the name and everything
                 * fileNames contains the information essential to populate the datagrid in the cropper.mxml
                ***************************************************************************************** ************************/
                public function selectionHandler(event:Event):void{
                    //trace("selection Handler ->>");
                    fileRef.removeEventListener(Event.SELECT, selectionHandler);
                    var numSelected:int = event.target.fileList.length;
                    var fileList:Array = event.target.fileList;
                    fileListx = new ArrayCollection();
                    fileListx = event.target.fileList as ArrayCollection;
                    //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: "",
                            itemDetails: item
                        });
                    }
                    var newListLength:Number = fileListArr.length;
                    if(myCounter > 0)
                        loopList(myCounter);
                    else
                        loopList(0);
                }

                /**************************************************************************************** *************************
                 * this function starts one, new filereference for each files in the array
                ***************************************************************************************** ************************/
                public function loopList(value:int):void{
                    //trace("looplist -->");
                    if(value < fileListArr.length){
                        _numCurrentUpload = value;       
                        file = new FileReference();
                        file = FileReference(fileListArr[value]);;
                        file.addEventListener(Event.COMPLETE, loadImage);
                        file.addEventListener(ProgressEvent.PROGRESS, fileProgress);
                        file.load();
                    }
                }

                /**************************************************************************************** *************************
                 * This function will convert the byte array into a string, and then it sends it to the server.
                ***************************************************************************************** ************************/
                public function loadImage(event:Event):void{
                    trace("loadImage -->");
                    file.removeEventListener(Event.COMPLETE, loadImage);
                        myCounter += 1;
                        var fileByteArr:ByteArray = event.target.data;
                        var b64En:Base64Encoder = new Base64Encoder();
                        b64En.encodeBytes(fileByteArr);
               
                        var str:String = b64En.flush();
                        imageData = new ImageData();
                        imageData.Base64EncodedImage = str;
                        imageData.FileName = event.target.name;
                        trace("sending -->>  " + imageData.FileName);
                        updateStatus("Sending to server");
                        imageService.addEventListener(ResultEvent.RESULT, imgServSuccess);
                        imageService.UploadImage(imageData);
                        b64En.reset();
                }
                /**************************************************************************************** *************************
                 * This function will decode the information recieved back from the server.
                 ***************************************************************************************** ************************/
                public function imgServSuccess(event:ResultEvent):void{
                    trace("imgServSuccess -->");
                    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;
                        }
                        dataToSave = new ImageData();
                        dataToSave = returnedData[0];
                        listCacheFiles.push(dataToSave);
                        updateStatus("Item in Cache");
                        //uploadDetails.visible = true;
                        loopList(myCounter);
                    }
                }
               
               
            /*****/
                public var win:itemDetails;

                public function itemClicking(event:Event):void{
                    var fileName:String = event.currentTarget.dataProvider[0].name;
                    for(var i:Number = 0; i < listCacheFiles.length; i++){
                       
                    }
                    //var temp:ImageData = event.target as ImageData;
                    win = null;
                    win = itemDetails(PopUpManager.createPopUp(this, itemDetails, true));
                    win.title = "Enter Details";
                    PopUpManager.centerPopUp(win);
                    win["save"].addEventListener("click", popupClosed);
                }
                public function popupClosed(event:Event):void{
                    var returnedData:ImageData = new ImageData;
                    returnedData = win.dataToSave;
                    saveImgAndData(returnedData);
                }
                public function saveImgAndData(data:ImageData):void{
                    saveImages = new Images;
                    saveImages.showBusyCursor = true;
                    saveImages.addEventListener(ResultEvent.RESULT, savedSuccess);
                    saveImages.addEventListener(FaultEvent.FAULT, faultFunc);
                    saveImages.SaveUploadedImageInformation(data);
                }
                public function faultFunc(event:FaultEvent):void{
                    Alert.show(event.fault.message);
                    Alert.show(event.fault.faultString);
                }   


                public function savedSuccess(event:ResultEvent):void{
                    //trace("savedSuccess -->");
                    var retMsg:Object = event.result.Images;
                    //trace("saving -->> " + retMsg[0].FileName);
                    updateStatus("Completed");
                    //loopList(myCounter);
                }

                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;
                }
               
                public function removeFiles():void{
                    var arrSelected:Array = displayFilesList.selectedIndices;
                    if(arrSelected.length >= 1){
                        for(var i:Number = 0; i < arrSelected.length; i++){
                            fileNames[Number(arrSelected[i])] = null;
                        }
                        var idx:int = 1;
                        for(var j:Number = 0; j < fileNames.length; j++){
                            if(fileNames[j] == null){
                                fileNames.removeItemAt(j);
                                j--;
                            }else{
                                fileNames[j].num = idx++;
                            }
                        }
                       
                        if(fileNames.length > 0)
                            displayFilesList.selectedIndex = 0;
                        else
                            displayFilesList.selectedIndex = -1;
                       
                        _numCurrentUpload--;
                        updateProgBar();
                    }

                }
               
                private function updateStatus(status:String, index:Number = -1):void{
                    index = _numCurrentUpload;
                    fileNames[index].status = status;
                    displayFilesList.invalidateList();
                }
               
                public function fileProgress(event:ProgressEvent):void{
                    //trace("fileProgress -->");
                    var numPerc:Number = Math.round((Number(event.bytesLoaded) / Number(event.bytesTotal)) * 100);
                    updateStatus("Uploading: " + numPerc.toString() + "%");
                    updateProgBar(numPerc);
                    var evt:ProgressEvent = new ProgressEvent("uploadProgress", false, false, event.bytesLoaded, event.bytesTotal);
                    dispatchEvent(evt);
                }
               
                public function updateProgBar(numPerc:Number = 0):void{
                    //trace("updateProgBar -->");
                    var strLabel:String = (_numCurrentUpload + 1) + "/" + fileNames.length;
                    progBar.label = strLabel;
                    progBar.setProgress(_numCurrentUpload + numPerc / 100, fileNames.length);
                    progBar.validateNow();
                }