What steps should I take to resolve the "undefined property match cannot be read" error that's showing up in this code?

Currently, I am facing an issue while attempting to integrate the nativescript-imagepicker plugin into my Nativescript App. I keep receiving an error message stating **cannot read **property match of undefined**. Below is a summary of the steps I have taken so far. Your assistance is greatly appreciated.

function onSelectSingleTap(args) {  
    var context = imagepickerModule.create({
        mode: "single"
    });
    if (platformModule.device.os === "Android" && platformModule.device.sdkVersion >= 23) {   
        permissions.requestPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE, "I need these permissions to read from storage")
        .then(function() {
            console.log("Permissions granted!");
            startSelection(context);
        })
        .catch(function() {
            console.log("Uh oh, no permissions - plan B time!");
        });
    } else {
        startSelection(context);
    }
}

function sendImages(selected) {
    let fileUri = selected.fileUri;
    imageName = extractImageName(fileUri);

    var request = {
        url: "http://vvvvvv.com/skog/upload.php",
        method: "POST",
        headers: {
            "Content-Type": "application/octet-stream",
            "File-Name": imageName
        },
        description: "{ 'uploading': " + imageName + " }"
    };
    //get the image source and upload from there
    selected.getImage().then(imageSource => {
        let temp = fs.knownFolders.temp();
        let uniqueName = '_' + Math.random().toString(36).substr(2, 9);
        let filePath = fs.path.join(temp.path, uniqueName + ".jpg");
        let saved = imageSource.saveToFile(filePath, enums.ImageFormat.jpeg);
        console.log(`item saved:${saved}`);
        var task = session.uploadFile(filePath, request);

        task.on("progress", logEvent);
        task.on("error", logEvent);
        task.on("complete", x => cleanFile(filePath));
    });
    //return task;
}
function logEvent(e) {      
        console.log("----------------");
        console.log('Status: ' + e.eventName);
        console.log('Error: ' + e.error);
        // console.log(e.object);
        if (e.totalBytes !== undefined) {
            console.log('current bytes transfered: ' + e.currentBytes);
            console.log('Total bytes to transfer: ' + e.totalBytes);
        }  
    }
function cleanFile(file){
    fs.remove(file);
}
function startSelection(context) {
    context
        .authorize()
        .then(function() {
            imageItems.length = 0;
            return context.present();
        })
        .then(function(selection) {
            selection.forEach(function(selected) {
                sendImages(selected);
                //selected.uploadTask = sendImages(selected);             
                selected.imageName = imageName;

                console.log("----------------");
                console.log("uri: " + selected.uri);           
                console.log("fileUri: " + selected.fileUri);
                console.log('Image name:' + imageName);

                imageItems.push(selected);
            });
            //list.items = selection;
        }).catch(function (e) {
      console.log(e);
      alert(e.message);
        });
}
function extractImageName(fileUri) {
  var pattern = /[^/]*$/;
  var imageName = fileUri.match(pattern);

  return imageName[0];
}

I have excluded the PHP code as I believe the issue does not lie there. However, if you suspect otherwise, please let me know. Your assistance is much appreciated.

Answer №1

Assortment is a collection of ImageAsset items, hence chosen.getPicture() inevitably results in undefined. The only available method is getPictureAsync(...) which retrieves image data in its native form.

In order to generate an ImageSource from an asset, the preferred approach is to utilize the fromAsset function.

filePath similarly yields undefined, suggesting the absence of such a property. The origins of these details remain vague. It is advisable to consult the documentation to validate all viable properties and methods.

Answer №2

this code snippet will accomplish the task

function handleSingleTap(args) {
      var picker = imagepickerModule.create({
          mode: "single"
      });

      if (platformModule.device.os === "Android" && platformModule.device.sdkVersion >= 23) {
          permissions.requestPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE, "I need these permissions to read from storage")
              .then(function () {
                  console.log("Permissions granted!");
                  initiateSelection(picker);
              })
              .catch(function () {
                  console.log("No permissions - alternative plan required!");
              });
      } else {
          initiateSelection(picker);
      }
    }

    function initiateSelection(picker) {

      picker
          .authorize()
          .then(function () {

              return picker.present();
          })
          .then(function (selection) {
            selection.forEach(function(selected) {
              var file =  selected.android.toString();
              var url = "https://adekunletestprojects.000webhostapp.com/skog/upload.php";
              var name = file.substr(file.lastIndexOf("/") + 1);
              var bghttp = require("nativescript-background-http");
              var session = bghttp.session("image-upload");
              var request = {
              url: url,
              method: "POST",
              headers: {
                  "Content-Type": "application/octet-stream",
                  "File-Name": name
              },
            description: "Uploading " + name
        };

            var task = session.uploadFile(file, request);
            task.on("progress", progressHandler);
            return task;
            function progressHandler(e) {
              var toast = Toast.makeText("uploaded " + e.currentBytes + " / " + e.totalBytes);
              toast.show();
          }
            });
          }).catch(function (e) {
              console.log(e.eventName);
              alert(e.message);
          });
    }

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

showing the data in a textbox using AJAX retrieved information

I have a table where additional rows can be added by the user with the click of a JavaScript function. Each row contains a drop down list, and based on the selected value, an AJAX script fetches some values to display in corresponding textfields within th ...

Modifying JavaScript using JavaScript

I'm looking for a solution to change the URL of a button in sync with the iframe displayed on the screen using JavaScript. The challenge I'm facing is figuring out how to dynamically update the button's URL based on the iframe content. Here ...

I'm seeking assistance with a frontend script problem. I'm curious if there are alternative approaches to coding this script that may be more effective. Can anyone offer guidance on this?

As a frontend developer specializing in script injection, I have been utilizing Adobe Target to inject scripts. However, this method presents several challenges: 1. It is difficult to debug code errors as my HTML and CSS are wrapped inside ' ' a ...

Sending numerous messages from a single event using Socket.io

After an exhaustive search, I have yet to find a solution to my problem. I am attempting to send a message from the server every time it detects a file change in a specific directory. However, instead of sending just one message, it sends the same message ...

What could be causing the incorrect value of the endpoint of an element when utilizing a function?

By adding angles individually and then using ttheta (without calling a function to add angles and then using ttheta), the problem is resolved. However, can anyone explain why using a function here is incorrect or identify the issue that this function is ca ...

Guidelines for showcasing validation summary on an ASP.NET webpage with the help of Javascript

My asp.net form contains multiple required fields that need validation. I am looking to display a summary of all validations at the end of the form. Valid input controls have already been checked, now I just need the summary. Here is an example code s ...

"Clicking the button will clear the values in the input fields

I have encountered a strange issue that I've never seen before. When I try to input the value of scope upon clicking on <a>, everything works fine. However, if I have entered values in other inputs and then click on <a> again, the values i ...

Adjust choices in a dropdown menu based on the selection of another dropdown menu

I am attempting to create a scenario where selecting an option from one dropdown list will dynamically change the options available in the next dropdown list. You can find my code on jsfiddle <!DOCTYPE html> <html> <body> &l ...

Creating a copy of a div using jQuery's Clone method

I need help figuring out how to clone a div without copying its value. I've attempted various methods, but they all seem to include the value in the cloned element. This is the jQuery function I am currently using: $('#add_more').click(fu ...

The functionality of removing a class on the body element is ineffective when using pagepiling.js

After creating a website using pagepiling.js, I implemented a script that adds the 'active' class to the section currently in view. My goal was to add a specific class to the body when my section1 is considered active. Here's the initial app ...

Continuously incorporating Ajax requests into a queue

I'm currently tackling a new feature at work and find myself at a crucial point. Despite being unfamiliar with Ajax, I am determined to set up a manual queue to handle the requests instead of relying on the browser. After some research and referring t ...

Connect two radio buttons across separate forms

I am encountering an issue with two radio buttons that I am trying to link together. The problem arises because they are located in two separate form elements, causing them not to function as intended. It is important for the forms to be utilized in Bootst ...

What is causing the extra space on the right side of the box?

I've been struggling to align text next to an image inside a box. Desired outcome CSS: #roundedBox { border-radius: 25px; background: #363636; width: auto; height: auto; margin: 10%; display: flex; position: relative; ...

Ways to dynamically incorporate media queries into an HTML element

Looking to make some elements on a website more flexible with media rules. I want a toolbar to open when clicking an element, allowing me to change CSS styles for specific media rules. Initially thought about using inline style, but it turns out media rul ...

Chained module incorporating a specialized Angular form validation directive

I've been working on incorporating an angular form validation "plugin," but I've hit a roadblock trying to utilize the directive in a child module. As a test, I'm using the HighlightDirective example. @Directive({ selector: '[highligh ...

How can I handle pings in Discord using discord.js?

I've been working on a feature in my discord.js bot that responds to pings, but I'm running into issues. Even after trying <@BOTID> and @BOT#0000, the functionality is not behaving as expected. Here's the snippet of code I'm using ...

Conditional radio button disabling in Material-ui

Currently, I am developing a React application using material-ui. My goal is to disable all radio buttons within a RadioGroup when a specific event occurs, and then re-enable them once the event is no longer active. For example, when a button is clicked, ...

How can I create a cube with complete beveling using Three.js?

I'm struggling to create a beveled cube in my project. I have come across the THREE.ExtrudeGeometry snippet in the documentation here. However, when I tried it out, I only managed to achieve beveled sides on the top and bottom faces like this: https: ...

Preventing a timer from pausing in NextJS during periods of inactivity

Recently, I developed a straightforward timer application using Next.js that should continue counting even when the browser window is inactive. However, I noticed that if I switch to another window for approximately 5 minutes, the timer stops counting whi ...

Creating an express route for updating with various parameters: a step-by-step guide

I am trying to make an update to a specific attribute in a JSON object by using the fetch PUT method. I have set up a put function that takes in 2 URL parameters app.put('/trustRoutes/:id/:item', (req, res){ So far, I have been able to update t ...