ImageUpload function adds(+1 copy) to next upload,… whats wrong?

You must Login before you can answer or comment on any questions.

I have a problem with my image upload function that I don´t seem to figure out by myself. I hope someone can help me. The choose and upload image function works, but it work too good. When I upload the first image, it work as it should. One image is uploaded to my server. But when I continue by choosing or taking a new photo, it uploads two copies of the same photo. The third image I upload becomes uploaded tree times, the next four times and so it grows in copies uploaded each time. Only if I restart the app, it starts from one copy upload again, but grows +1.

Here is my image upload code:

— asked 10 months ago by Åge Engjom
1 Comment
  • //this variable will hold the image data blob from the device's gallery or camera
    var selectedImage = null;
     
    //our dialog with the options of where to get an 
    //image from
    var dialog = Titanium.UI.createOptionDialog({
        title: 'Choose source...',
        options: ['Camera','Album','Cansel'],
        cancel:2
    });
     
    //Dialog event listener
    dialog.addEventListener('click',function(e){
        Ti.API.info('You selected… ' + e.index);
        if(e.index == 0){
        //from the camera
        Titanium.Media.showCamera({
        success:function(event){
        selectedImage = event.media; 
        if(event.mediaType == Ti.Media.MEDIA_TYPE_PHOTO){
        imageThumbnail.image = selectedImage;
        win.add(imageThumbnail);
        imagesBackground.hide();            
        }
        buttonUpload.addEventListener('click', function(e){
        if(selectedImage != null) {
        postToSite();
        }else{
        alert('You must choose a image!');
        }
        });
        win.add(buttonUpload);
        },
        cancel:function(){
        //getting image from camera was cancelled
        },
        error:function(error){
        // create alert
        var a = Titanium.UI.createAlertDialog({title:'Camera'});
        // set message
        if (error.code == Titanium.Media.NO_CAMERA){
        a.setMessage('Your cellphone lack the camera function!');
        }else{
        a.setMessage('Unexpected error: ' + error.code);
        }
        // show alert
        a.show();
        },
        allowImageEditing:true,
        saveToPhotoGallery:true
        });
        }
        else if(e.index == 1){
        //obtain an image from the gallery
        Titanium.Media.openPhotoGallery({
        success:function(event){
        selectedImage = event.media;
     
        // set image view
        Ti.API.debug('Our type was: '+event.mediaType);
        if(event.mediaType == Ti.Media.MEDIA_TYPE_PHOTO){
        // set image view
        imageThumbnail.image = selectedImage;
        win.add(imageThumbnail);
        imagesBackground.hide();
        }
        buttonUpload.addEventListener('click', function(e){
        if(selectedImage != null) {
        postToSite();
        }else{
        alert('You must choose a image!');
        }
        });
        win.add(buttonUpload);      
        },
        cancel:function(){
        //user cancelled the action fron within
        //the photo gallery
        }
        });
        }else{
        //cancel was tapped
        //user opted not to choose a photo
        }
    });
     
    win.add(buttonSelectImage);
     
    function randomString(length,current){
    current = current ? current : '';
    return length ? randomString( --length , "abcdefghiklmnopqrstuvwxyz".charAt( Math.floor( Math.random() * 60 ) ) + current ) : current;
    }
    //Post to server
    function postToSite(){
        //create the httpRequest
        var xhr = Titanium.Network.createHTTPClient();
        xhr.onerror = function(e)
            {
                Ti.UI.createAlertDialog({title:'Error', message:e.error}).show();
                Ti.API.info('IN ERROR ' + e.error);
            };
            xhr.setTimeout(40000);
            
        xhr.onload = function(e)
            {
                Ti.UI.createAlertDialog({title:'Success', message:'status code ' + this.status}).show();
                Ti.API.info('IN ONLOAD ' + this.status + ' readyState ' + this.readyState);
            };
        xhr.onsendstream = function(e){
                
                ind.value = e.progress ;
                Ti.API.info('ONSENDSTREAM - PROGRESS: ' + e.progress);
                ind.show();
            };
                
        // Get the sessionID
        var sessionId = Titanium.App.Properties.getString("sessionId");
        
        //open the httpRequest
        xhr.open('POST','http://example.com/index.php?include=app_support/upload.php&session_id='+sessionId);
            activityIndicator.show();
            buttonUpload.hide();
        xhr.onload = function(){
            //the image upload method has finished
            var json = this.responseText;
            var response = JSON.parse(json);
            if (response.auth == 'false'){
                alert('User validation failed');
            }
            else if (response.upload_status == 'success'){
                ind.hide();
                activityIndicator.hide();
                buttonUpload.hide();
                alert(response.message);
            }else{
                ind.hide();
                activityIndicator.hide();
                buttonUpload.show();
                alert(response.message);
            }
        };
        //send the data
        var r = randomString(5) + '.jpg';
        xhr.send({'form_data[file][value]': selectedImage, 'value': r});
    }

    — commented 10 months ago by Åge Engjom

1 Answer

Could it be because you have 2 xhr.onload events?

— answered 10 months ago by Josh Lewis
answer permalink
2 Comments
  • Thank you for your observation, I had overlooked it myself. But when I deleted the first xhr.onload -it did not change this strange behavior. It still adds on in copies when I upload photos.

    — commented 10 months ago by Åge Engjom

  • Here are the changed code:

    //our dialog with the options of where to get an 
    //image from
    var dialog = Titanium.UI.createOptionDialog({
        title: 'Choose source...',
        options: ['Camera','Album','Cansel'],
        cancel:2
    });
     
    //Dialog event listener
    dialog.addEventListener('click',function(e){
        Ti.API.info('You selected… ' + e.index);
        if(e.index == 0){
        //from the camera
        Titanium.Media.showCamera({
        success:function(event){
        selectedImage = event.media; 
        if(event.mediaType == Ti.Media.MEDIA_TYPE_PHOTO){
        imageThumbnail.image = selectedImage;
        win.add(imageThumbnail);
        imagesBackground.hide();            
        }
        buttonUpload.addEventListener('click', function(e){
        if(selectedImage != null) {
        postToSite();
        }else{
        alert('You must choose a image!');
        }
        });
        win.add(buttonUpload);
        buttonUpload.show();
        },
        cancel:function(){
        //getting image from camera was cancelled
        },
        error:function(error){
        // create alert
        var a = Titanium.UI.createAlertDialog({title:'Camera'});
        // set message
        if (error.code == Titanium.Media.NO_CAMERA){
        a.setMessage('Your cellphone lack the camera function!');
        }else{
        a.setMessage('Unexpected error: ' + error.code);
        }
        // show alert
        a.show();
        },
        allowImageEditing:true,
        saveToPhotoGallery:true
        });
        }
        else if(e.index == 1){
        //obtain an image from the gallery
        Titanium.Media.openPhotoGallery({
        success:function(event){
        selectedImage = event.media;
     
        // set image view
        Ti.API.debug('Our type was: '+event.mediaType);
        if(event.mediaType == Ti.Media.MEDIA_TYPE_PHOTO){
        // set image view
        imageThumbnail.image = selectedImage;
        win.add(imageThumbnail);
        imagesBackground.hide();
        }
        buttonUpload.addEventListener('click', function(e){
        if(selectedImage != null) {
        postToSite();
        }else{
        alert('You must choose a image!');
        }
        });
        win.add(buttonUpload);
        buttonUpload.show();        
        },
        cancel:function(){
        //user cancelled the action fron within
        //the photo gallery
        }
        });
        }else{
        //cancel was tapped
        //user opted not to choose a photo
        }
    });
     
    win.add(buttonSelectImage);
     
    function randomString(length,current){
    current = current ? current : '';
    return length ? randomString( --length , "abcdefghiklmnopqrstuvwxyz".charAt( Math.floor( Math.random() * 60 ) ) + current ) : current;
    }
    //Post to server
    function postToSite(){
        //create the httpRequest
        var xhr = Titanium.Network.createHTTPClient();
        xhr.onerror = function(e)
            {
                Ti.UI.createAlertDialog({title:'Error', message:e.error}).show();
                Ti.API.info('IN ERROR ' + e.error);
            };
            xhr.setTimeout(40000);
            
        xhr.onsendstream = function(e){
                
                ind.value = e.progress ;
                Ti.API.info('ONSENDSTREAM - PROGRESS: ' + e.progress);
                ind.show();
            };
                
        // Get the sessionID
        var sessionId = Titanium.App.Properties.getString("sessionId");
        
        //open the httpRequest
        xhr.open('POST','http://example.com/index.php?include=app_support/upload.php&session_id='+sessionId);
            activityIndicator.show();
            buttonUpload.hide();
        xhr.onload = function(){
            //the image upload method has finished
            var json = this.responseText;
            var response = JSON.parse(json);
            if (response.auth == 'false'){
                alert('User validation failed');
            }
            else if (response.upload_status == 'success'){
                ind.hide();
                activityIndicator.hide();
                buttonUpload.hide();
                alert(response.message);
            }else{
                ind.hide();
                activityIndicator.hide();
                buttonUpload.show();
                alert(response.message);
            }
        };
        //send the data
        var r = randomString(5) + '.jpg';
        xhr.send({'form_data[file][value]': selectedImage, 'value': r});
    }

    — commented 10 months ago by Åge Engjom

Your Answer

Think you can help? Login to answer this question!