While utilizing Ionic to upload images to a server, I encountered the FileTransferError error code 3

I have successfully uploaded an image from the gallery, but I am facing issues while uploading multiple images at once.

Here is the code snippet I am using:


pictureUpload(x){ // x represents the file path like - file:///storage/emulated/0/Download/palakkeni.jpg
  if(this.network.noConnection()){
          this.network.showNetworkAlert()
      }else{
          let loading = this.loadingCtrl.create({
            spinner: 'bubbles',
            content: 'Uploading your Picture...'
          });
          loading.present();
          var fileArray = x.split("/");
          let len = fileArray.length;
          var file = fileArray[len - 1];
          let fileTransfer: FileTransferObject = this.transfer.create();;     
          let option: FileUploadOptions = {
            fileKey: 'img',
            fileName: x,
            mimeType: "multipart/form-data",
            headers: {
               authorization : 'e36051cb8ca82ee0Lolzippu123456*='
            },
            params: {
               name: file,
               id: this.empid
            }
          }
          this.completed = false;
          fileTransfer.upload(x, encodeURI("http://forehotels.com:3000/api/upload_employee_image"), option, true)
          .then((data) => {
             this.completed=true;
             loading.dismiss()
             console.log("image uploaded")
           }, (err) => {
             loading.dismiss()
             console.log(err)
          let alert = this.alertCtrl.create({
             title: err.text(),
             subTitle: err.json(),
             buttons: ['Dismiss'],
          });
          alert.present();
          });
        this.view_picture = file;
        this.picture=x
        this.uploaded++              
      }
  }

The error output I'm receiving is as follows:


FileTransferError
body: null
code: 3
exception: "Permission denied (missing INTERNET permission?)"
http_status: null
source: "file:///storage/emulated/0/Download/xyz.jpg"
target: "http://companydomainname.com:3000/api/upload_employee_image"

Here is the output of 'ionic info' on my system:

Ionic:

Ionic CLI : 5.1.0 (C:\Users\pramo\AppData\Roaming\npm\node_modules\ionic) Ionic Framework : ionic-angular 3.9.2 @ionic/app-scripts : 3.2.4

Cordova:

Cordova CLI : 9.0.0 ([email protected]) Cordova Platforms : android 8.0.0, browser 5.0.4 Cordova Plugins : cordova-plugin-ionic-keyboard 2.1.2, cordova-plugin-ionic-webview 1.2.1, (and 18 other plugins)

Utility:

cordova-res : 0.4.0 native-run : 0.2.6

System:

NodeJS : v10.15.3 (C:\Program Files\nodejs\node.exe) npm : 6.4.1 OS : Windows 10

The list of cordova plugins installed in my project includes:


cordova-android-support-gradle-release 3.0.0 "cordova-android-support-gradle-release"

cordova-plugin-app-version 0.1.9 "AppVersion"

cordova-plugin-calendar 5.1.0 "Calendar"

cordova-plugin-contacts 3.0.1 "Contacts"

....

If anyone can guide me on why I am encountering this error and help resolve it, I would greatly appreciate it.

Answer №1

The android.permission.INTERNET permission is not present. To include it, add the following line to your config.xml file or AndroidManifest.xml:

<uses-permission android:name="android.permission.INTERNET"/>

Answer №2

Appreciate the help from everyone who provided answers. I managed to resolve my issue, although in a quite unconventional manner. Initially, I was unable to locate AndroidManifest.xml in platforms/android

Instead, I came across a file named android.json within platforms/android/android.json

Upon reviewing the contents of the file, I discovered the following code:

"AndroidManifest.xml": {
        "parents": {
          "/manifest": [
            {
              "xml": "<uses-permission android:name=\"android.permission.READ_CALENDAR\" />",
              "count": 1
            },
            ...
            }
          ]
        }
      }

Please disregard the closing brackets mentioned.

However, I made edits to the code and inserted the following:

{
              "xml": "<uses-permission android:name=\"android.permission.INTERNET\" />",
              "count": 1
            }

This adjustment effectively resolved my problem

Answer №3

Perhaps the issue is not related to permissions in this case. I encountered a similar problem and was able to resolve it by granting read and write permissions.

this.androidPermissions.checkPermission(this.androidPermissions.PERMISSION.READ_EXTERNAL_STORAGE).then(
  result => {
    if (!result.hasPermission) {
      this.androidPermissions.requestPermission(this.androidPermissions.PERMISSION.READ_EXTERNAL_STORAGE)
    }
  }
)
this.androidPermissions.checkPermission(this.androidPermissions.PERMISSION.WRITE_EXTERNAL_STORAGE).then(
  result => {
    if (!result.hasPermission) {
      this.androidPermissions.requestPermission(this.androidPermissions.PERMISSION.WRITE_EXTERNAL_STORAGE)
    }
  }
)

Next, make sure to:

cordova plugin add cordova-plugin-whitelist
cordova prepare

Also, include the following line in your config.xml file:

<allow-navigation href="*" />

Answer №4

Here is a suggestion for you to try out: Include the following modules:

import { FileTransfer, FileUploadOptions, FileTransferObject } from '@ionic-native/file-transfer';
import { File } from '@ionic-native/file';


uploadImage(imagePath) { // imagePath represents the File_URI obtained from the Camera Plugin
  const fileTransfer: FileTransferObject = this.transfer.create();
  let options: FileUploadOptions = {
      fileKey: 'image',
      fileName: '.png',
      chunkedMode: false,
      //mimeType: "image/jpeg",
    }
    fileTransfer.upload(imagePath, 'Server-URL', options)
      .then((data) => {
      console.log(data+" Uploaded Successfully");          
    }, (err) => {
      console.log(err);
    });
}

Don't forget to grant Internet Permission in your config.xml configuration file as well.

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

Mastering the Art of Injecting Objects from the Server

Utilizing Angular Universal, I am serving my Angular application through an Express server. The objective is to embed an environment object (from the server) into my application. To achieve this, I have created an InjectionToken export const ENVIRONMENT ...

Error encountered in Angular2: Attempted to access property 'compilerOptions' which is undefined

I encountered a TypeError: Unable to access the 'compilerOptions' property of undefined Below is the snippet of my compilerOptions code: { "compilerOptions": { "target": "ES5", "module": "commonjs", "emitDecoratorMetadata": tr ...

Custom "set attribute" feature in TypeScript

One issue I faced was resolved by creating the function shown below : function setProperty<T extends Record<string, string>>(obj: T, key: keyof T) { obj[key] = "hello"; } However, when I tried to compile the code, I encountered an ...

TS2304: 'Omit' is a mysterious being that cannot be located

Encountered an issue while compiling my Angular project. This is a project that has remained unchanged for some time and is built daily by Jenkins. However, today it started failing and I'm struggling to determine the cause. ERROR in [at-loader] ./no ...

Django and Angular combine to create a floral mapping feature that allows users to easily return to their task list

I am looking to arrange the output from the flower library (/api/tasks) into a list of objects. The current response includes multiple objects, but lacks a "list wrapper", making it difficult to iterate over. API: An example of the return is as follows: H ...

Discovering ways to fetch an array of objects using object and arrays in JavaScript

When comparing an array of objects with a single object and listing the arrays in JavaScript, specific conditions need to be met to retrieve the array of objects: If the itemvalue and idvalue are the same, check if the arrobj cid has the same codevalue ...

[ERROR] There was a problem encountered during the execution of the ionic-app-scripts subprocess

I encountered an error while running my Ionic project. Below is the error message: [ERROR] ionic-app-scripts has unexpectedly closed (exit code 1). The Ionic CLI will exit. Please check any output above for error details. ionic3-firebase-shopping-car ...

Suggestions for enhancing or troubleshooting Typescript ts-node compilation speed?

Recently, I made the switch to TypeScript in my codebase. It consists of approximately 100k lines spread across hundreds of files. Prior to the migration, my launch time was an impressive 2 seconds when using ESLint with --fix --cache. However, after impl ...

Universal Parameter Typing in Functions

I'm grappling with a concept that seems obvious to me, yet is disallowed by Typescript when all strict flags are enabled (presumably for valid reasons). Let me illustrate: We all understand the following: export interface Basic { value: "foo&q ...

How can I capture the click event on the oktext in Ionic?

When using Ionic, I have a select button with options for okText and cancelText. The issue I am facing is that when I click on okText, the menu closes as expected due to this attribute. However, I am interested in implementing it through click events. Belo ...

Organizing Angular models and interfaces

The Angular styleguide provides best practices for using classes and interfaces in applications, but it does not offer guidance on organizing interfaces and model classes. One common question that arises is: what are the best practices for organizing file ...

Material-UI: Error thrown when attempting to pass props to makeStyles in React due to missing property 'X' on type '{}'

Currently experimenting with Adapting based on props, you can find more information here import React from 'react'; import { makeStyles } from '@material-ui/core'; const useStyles = makeStyles({ // style rule foo: props => ( ...

Creating the data type for the input file's state: React with Typescript

Encountering an error when attempting to define the type of a file object within state: Argument of type 'null' is not assignable to parameter of type 'File | (()=> File)'.ts. Currently working on an upload component that allows for ...

Error TS2322: Cannot assign type 'Foo | Bar' to type 'Foo & Bar'

I am attempting to save an item in an object using the object key as the discriminator for the type. Refer to the edit below. Below is a simple example: type Foo = { id: 'foo' } type Bar = { id: 'bar' } type Container = { foo ...

Clear drop down selections after button is pressed

I am currently working with a grid in my template that contains multiple dropdowns, each row having its own. When I click a button, I gather the values from these dropdowns. However, upon clicking this button, I wish to reset all the dropdowns back to thei ...

Transform the function into an observable form

Is there a way to transform this function into an observable? I need it to check for the existence of a document based on a query, and I want to be able to subscribe to it in order to create a new document if one does not already exist. Unfortunately, I a ...

Dealing with "Cannot find name" errors in Typescript when working with React components

I'm currently in the process of transitioning my React code to TypeScript, and I've encountered numerous challenges. One recurring issue is the "Cannot find name" errors that pop up when converting my .js files to .ts files. Let's take a lo ...

Steps for clicking on the center of a leaflet map with protractor

I'm currently facing an issue where I am attempting to click on the center of a map located in the second column of the webpage, which has an offset. However, I am encountering a problem where the cursor always points to the center of the page instead ...

Unable to locate any static exports within the TypeScript library bundle

In my file Style.ts, I have a class called Style: export class Style { ... } The Style class consists of properties, methods, and a constructor, along with import statements for other class dependencies. It is being used by other classes through the ...

How to effectively handle null values using try..catch statement in typescript

As a beginner, I am learning how to write a try/catch statement in TypeScript. My issue is that there is a function within the "try" block that returns null. How can I implement code in the "catch" block specifically for when the function in "try" returns ...