The picture was not uploaded via Cordova's Android file transfer

I've set up a page that allows users to either take a photo or choose one from their phone's gallery, and it's functioning as expected. However, I'm looking to now upload the selected photo to my server on my Godaddy hosting. To achieve this, I integrated the Cordova file transfer plugin by executing the following command in the terminal:

 cordova plugin add https://github.com/apache/cordova-plugin-file-transfer.git

Afterwards, I wrote a brief snippet of code to upload the selected photo, but I'm not receiving any alert messages (neither error nor success).

Here is the code snippet used to select an image:

    function onPhotoURISuccess(imageURI) {
            // Uncomment to view the image file URI
            // console.log(imageURI);

            // Get image handle
            //
            var largeImage = document.getElementById('largeImage');

            // Unhide image elements
            //
            largeImage.style.display = 'block';

            // Display the captured photo
            // The in-line CSS rules are used to resize the image
            //
            largeImage.src = imageURI;

            upload();
        }

Code for the Upload function:

 function upload() {
            alert('large');
            var uploadingImage = document.getElementById('largeImage');
            var imgUrl = uploadingImage.src;
            window.resolveLocalFileSystemURI(imgUrl, resolveOnSuccess, fsFail);
            options = new FileUploadOptions();
            // parameter name of file:
            options.fileKey = "my_image";
            // name of the file:
            options.fileName = imgUrl.substr(imgUrl.lastIndexOf('/') + 1);

            // mime type:
            options.mimeType = "image/jpeg";
            params = {val1: "some value", val2: "some other value"};
            options.params = params;
            ft = new FileTransfer();
            ft.upload(fileuri, "http://siencelb.org/raycoding/insurance/avatar", success, fail, options);
        }
 function resolveOnSuccess(entry) {
            fileuri = entry.toURL();
            //use fileuri to upload image on server
        }

        function fsFail(message) {
            alert("Error Message: " + message + "Error Code:" + message.target.error.code);
        }

I have included two buttons on the page - the first button allows users to select an image, which is then displayed in the 'largeImage' div and this functionality is working correctly. The second button is intended to upload the selected image. It's worth noting that the alert('large') message is being displayed.

Answer №1

After successfully solving an error, I am eager to share my solution with others.

function captureImage() {
            navigator.camera.getPicture(function(imageURI) {
                var imgElement = document.getElementById('camera_image');
                imgElement.style.visibility = "visible";
                imgElement.style.display = "block";
                imgElement.src = imageURI;
                document.getElementById('camera_status').innerHTML = "Success";
            }, function(error) {
                console.log("Error getting picture: " + error);
                document.getElementById('camera_status').innerHTML = "Error getting picture.";
            }, {quality: 50, destinationType: navigator.camera.DestinationType.FILE_URI});
        }
        ;
        /** * Choose image from library */
        function chooseImage() {
            navigator.camera.getPicture({quality: 50, destinationType: navigator.camera.DestinationType.FILE_URI, sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY});
        }
        ;


function uploadImage() {      // Retrieve image URI to upload
            var imgElement = document.getElementById('camera_image');
            var imageURI = imgElement.src;
            if (!imageURI || (imgElement.style.display == "none")) {
                document.getElementById('camera_status').innerHTML = "Take picture or select picture from library first.";
                return;
            }        // Check if server URL is provided
            server = "upload.php";
            if (server) {               // Define transfer options
                var options = new FileUploadOptions();
                options.fileKey = "file";
                options.fileName = imageURI.substr(imageURI.lastIndexOf('/') + 1);
                options.mimeType = "image/jpeg";
                options.chunkedMode = false; // Transfer picture to server
                var fileTransfer = new FileTransfer();
                fileTransfer.upload(imageURI, server, function(response) {
                    document.getElementById('camera_status').innerHTML = "Upload successful: " + response.bytesSent + " bytes uploaded.";
                }, function(error) {
                    document.getElementById('camera_status').innerHTML = "Upload failed: Code = " + error.code;
                }, options);
            }
        }

the PHP code of upload.php

<?php
// Directory where uploaded images are saved
$dirname = "/avatar/"; 
// Check if files are being uploaded
if ($_FILES) {  
print_r($_FILES);  
mkdir ($dirname, 0777, true);  
move_uploaded_file($_FILES["file"]["tmp_name"],$dirname."/".$_FILES["file"]["name"]);}
?>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Stop images from appearing transparent when placed inside a transparent div

My issue is clearly visible in this image: The div element is transparent and affecting the images inside it. Below is my HTML code: <div id="cselect" style="position: absolute; top: 99px; left: 37px; display: block;"> <div class="cnvptr"> ...

What is the best way to enable object references in Node modules?

I've been working on my Express.js web app and I've realized that as I extract parts of my code from the main app.js file into separate modules, I sometimes need to access objects from the main file. I'm trying to figure out the best way to ...

Sending an Ajax request using a dropdown menu

I'm having trouble retrieving a value from my database when a select option is chosen. The select options are generated dynamically from the same database. As a beginner in AJAX requests, I am struggling to figure out why I am only getting a blank re ...

How can I create a detailed highchart map of Korea that accurately includes Dokdo in its design?

I am currently working on a project to create a comprehensive map of Korea using highchart. One major challenge I have encountered is the absence of Dokdo on the standard map of Korea provided by highchart. Is there a way for me to develop a map that inc ...

Conceal the parent component's <button> element within the Child component

I'm facing an issue with hiding a button in my parent component from the child component. I tried using props to bind the element and v-show directive to hide it, but instead of just hiding the button, it ends up hiding the entire tab. Take a look at ...

Executing an ajax request following validation

I am facing an issue with my ajax insert script and validation script. Currently, the insert script is executing regardless of the validation result. How can I modify my code to ensure that the insert query only runs after successful validation? Below is ...

Implementing Canvas Offset in a jQuery Mobile Environment

I have positioned a pen ready for use at this location. http://codepen.io/prantikv/pen/LEbRKY Currently, I am utilizing a canvas to track mouse movements or touch input. It performs as expected when jQuery or jQuery mobile is not included. However, upon ...

Using the foreach loop within the Alert.alert function in React Native

function displayModal(modalarray) { return Alert.alert( "Modal Title", "Alert Message", [ modalarray.forEach(element => { "{text: element, onPress: () => console.log('button press)},"; }) ], ...

What is the best way to divide a string into an array containing both linked and non-linked elements?

I'm struggling to find the right solution to my problem. I need to create a view that is enclosed in a clickable div. The content will consist of plain text mixed with clickable URLs - the issue arises when clicking on a link also triggers the method ...

What are some ways to implement querySelectorAll in conjunction with htmx?

I'm currently using htmx, an amazing library with a small issue that I'm struggling to resolve. htmx utilizes querySelector to find elements for swapping or updating, for example with hx-swap="...", hx-target="...". How can I use querySelectorAll ...

Retrieve the JSON object with an AJAX request that contains three arrays, then transfer these arrays to JavaScript

A web page I designed generates the following content: <script> var JSONObject = { "groups":['1210103','1210103','1210103','1210405'], "prices":['279,00','399,00',&ap ...

Error: Validation issues detected in field functionality

My goal is to loop through a set of text fields and check if the user has input any values. However, I'm facing an issue where even though I have provided values in the text fields, it seems like they are empty. To better illustrate my problem, I have ...

Operating with a multidimensional entity

I am aiming for an object structure like this: {"Red 1":53,"Blue 2":26,"Green 3":25} Based on the following example: I attempted to push data from within .each loop into the object. However, due to its multidimensional nature, I'm uncertain how to ...

The media parameter seems to be malfunctioning when attempting to send it to the Kaleyra API using code

Attempting to send media through the Kaleyra API using my code is proving unsuccessful. However, when I make the same request via Postman, it works perfectly fine. async whatsappAPIWithAttachment(requestBody) { let api_key = ""; if (requ ...

What is the significance of static in react?

export class NavMenu extends Component { static displayName = NavMenu.name; constructor (props) { super(props); this.toggleNavbar = this.toggleNavbar.bind(this); this.state = { collapsed: true }; } I attempted to research the ...

Sending an array input to PHP

I am having trouble sending an array input to PHP via JavaScript. The posted array does not seem to be showing up in the controller when I try to print it. Here is the relevant code snippet: submitHandler: function(form) { $('input[name="val_prof ...

JavaScript form validation eliminates input data

I recently started using the JavaScript library for client-side form validation called Bouncer. It has been working really well, but I have encountered a peculiar behavior that I need help understanding. My form has two submit buttons with different value ...

Prevent inputting values into the text field

Below is the code I wrote to prevent users from entering certain values in a textbox: $(".block-keypress").keypress(function(e){ return false; }); While the code is functioning properly, the backspace key is not blocked. ...

"Resolving the problem of populating an empty array with JSON

My JSON structure at the top level is set up like this: { "video": [], "messages": [], "notifications": [] } In the database output stored in a variable called "result," I have data that I want to add to the "vide ...

The sign-up button mysteriously vanishes after the page is refreshed

I am encountering an issue with the sign up button during the user registration process. There is a checkbox for Terms & Conditions, and the button should only become enabled after checking this box. Everything seems to be functioning correctly, but when I ...