Error Code 1: Cordova FileTransfer Writing Issue

In my Android application using Cordova 4.2.0, I am experiencing challenges with getting the FileTransfer plugin to function correctly. It seems like there might be an error in the code.

exception:".myApp\/contentImages\/20150110220101.jpg: open failed: ENOENT (No such file or directory)"

The filename has been verified and it does not exist yet:

rootFS.getFile('.myApp/contentImages/'+file,{create:false},
    function(){
        console.log(file+' already exists');
    },
    function(error){
        console.log(file+" does not exist locally");
        console.log("Error #"+error.code);
        download(file);
    }
);

Below is the code for the download function:

function download (filename){
    var localPath = rootFS.fullPath+'/.myApp/contentImages/'+filename;
    var fileTransfer = new FileTransfer();
    fileTransfer.download(
        encodeURI('http://distantApp/contentImages/'+filename), // This file exists
        localPath,
        function(entry) {
            console.log("download complete: " + entry.fullPath);
        },
        function (error) {
            console.log('download error: ' + error.code + ": "+error.exception+" ; source " + error.source+" ; target " + error.target);
        }
    );
}

I am trying to identify what could potentially be causing the issue.

EDIT Code snippet for rootFS:

function onDeviceReady(){
    window.requestFileSystem  = window.requestFileSystem || window.webkitRequestFileSystem;
    window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, function(){
        console.log("error requesting LocalFileSystem");
    });
}
function gotFS(fileSystem) {
    console.log("got filesystem: "+fileSystem.name); // displays "persistent"
    console.log(fileSystem.root.fullPath); // displays "/"
    window.rootFS = fileSystem.root;
}

Answer №1

An issue arose due to an update of Cordova from an older version.

The issue stemmed from the incorrect identification of local file paths: .fullPath has been deprecated and should be substituted with .toURL().

Answer №2

Perhaps the issue lies not with the FileTransfer plugin, but rather with how you are attempting to verify the existence of the file.

Upon reviewing this resource: http://www.html5rocks.com/en/tutorials/file/filesystem/, it becomes evident that trying to access a file when its immediate parent does not exist will result in an exception:

When working within the callback function, using fs.root.getFile() to create a file is possible. It is important to provide a valid path—whether absolute or relative. Creating a file whose direct parent does not exist will generate an error.

It is worth considering whether the issue stems from non-existent parent directories for your file, such as .myapp and contentImages.

Answer №3

Issue code 1 may be related to accessibility problems. In my scenario, the issue stemmed from file permission issues. If you are using an SDK version lower than 29 (Android 10), it is necessary to prompt the user for read/write permissions.

Include cordova-plugin-android-permissions in your config.xml file

const filesPermissions = (permissions) => [
 permissions.READ_EXTERNAL_STORAGE,
 permissions.WRITE_EXTERNAL_STORAGE,
];

const checkFilesPermissions = async () => {
  const { permissions } = window.cordova.plugins;
  return Promise.all(filesPermissions(permissions).map(permission => {
    return new Promise((resolve, reject) => permissions.checkPermission(permission, resolve, reject));
  })).then(statuses => statuses.every(status => status.hasPermission));
};

const requestFilesPermissions = async () => {
    const { permissions } = window.cordova.plugins;
    return new Promise((resolve, reject) => {
        permissions.requestPermissions(filesPermissions(permissions), resolve, reject);
  }).then(status => status.hasPermission);
};

// Handle onClick event:

if (deviceService.isAndroidPlatform()) {
  try {
    let hasFilesPermissions = await checkFilesPermissions();
    if (!hasFilesPermissions) {
      hasFilesPermissions = await requestFilesPermissions();
    }
    if (!hasFilesPermissions) {
      throw new Error('Insufficient permissions to download files. Please enable them in system preferences');
    }
  } catch (error) {
    alert(error.message)
  }
}

// Proceed with downloading your file using cordova-plugin-file-transfer as usual

Note: Ensure that you have enabled READ_EXTERNAL_STORAGE and WRITE_EXTERNAL_STORAGE in your AndroidManifest.xml file

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

Can a variable be initialized with a concealed or additional argument?

After just 2 weeks of coding, I'm struggling to find information on how to initialize a variable with an extra argument in a recursive function call. Is this even possible? And if it is, are there any scenarios where it's considered best practice ...

Gulp is ensuring the destination file remains unchanged

I'm encountering an issue with gulp in my project. I've set up a process to automate the compilation of source and styles into a single file using gulp. However, I'm facing a problem where it doesn't want to overwrite the `application.j ...

Challenge with neglected open connections from a comet

Utilizing various comet techniques like long polling and forever frame, along with iframes for cross subdomain activities, has presented a challenge during implementation. When a user refreshes the page or navigates to another page, a new request is made w ...

What is the best way to achieve a partial match using JQuery?

I'm experimenting with this $("ul.nav-tabs a:contains('profile')").parent().addClass("active") It does not function properly if I include Profile in the text. Is there a way to make it case insensitive? ...

Guide to adding items to an array in json-server using a JavaScript-created database

I built a JSON-server app that dynamically generates the database using JavaScript when it starts running. The data I create is organized within a 'users' object, as illustrated below: { "users": [ { "id": "user_id_0", ...

Confirm the login form using JavaScript and PHP

I am working on a functionality where I need to either redirect a user to a restricted area or display a message saying Email and or password do not exist if the login credentials are incorrect. However, I'm facing issues as nothing happens regardless ...

The Nginx location directive is failing to properly handle certain URLs

Currently, I have the following setup: location /ron-swanson-quotes/ { return 301 /ron-swanson/; } Along with a SSR React app in next.js. The redirect mentioned above works perfectly for site visitors who come from an external source, but it fails whe ...

Is there a way to locate and delete an image element with a broken hyperlink?

My website is currently hosted on Wordpress, and I've noticed that there is an issue with a broken image link on my site. I'm not sure when this occurred, but it seems to only be affecting the post section of my site. https://i.sstatic.net/iarDU ...

The optimal method for loading CSS and Javascript from an ajax response within a JavaScript function - Ensuring cross-browser compatibility

I am in a situation where I need jQuery to make sense of an ajax response, but due to latency reasons, I cannot load jQuery on page load. My goal is to be able to dynamically load javascipt and css whenever this ajax call is made. After reading numerous a ...

Using jQuery, how can I add value to every input when the option is changed?

I need help changing the values of all input:text elements based on selections from a select menu. Specifically, I want to change only the matched td.class values from the data-pset attribute inside the <select>. As a beginner in jQuery, I can only ...

Ways to conceal a button or textView during the integration of screen recording

Imagine a scenario where there is a screen with numerous buttons and textViews. If a user tries to take a screenshot or screen record while using the application, certain views should not be captured. Is there a method to achieve this? ...

Is there a Webpack plugin available that can analyze the usage of a function exported in a static

Just to clarify, I am presenting this theoretical scenario on purpose, as it reflects a genuine issue that I need to solve and am uncertain if it's feasible. Imagine I have a JavaScript package named road-fetcher, containing a function called find wh ...

What steps should I take to troubleshoot and resolve the connection issue that arises while trying to execute npm install

Following the guidelines from: https://www.electronjs.org/docs/tutorial/first-app I executed commands like mkdir, cd, and npm init. They all ran successfully, generating a file named package.json. Subsequently, I entered npm install --save-dev electron w ...

Flag is to be set while moving through the input fields

I am currently working on a form with multiple text fields and a text area. I have implemented a loop to go through each of these fields and check if there is a value present. If the field is empty, I set a flag to pass=false. On the other hand, if a value ...

Maximizing memory efficiency during resume operations

Writing this question based on a few important facts. One of them being that we cannot control the Garbage Collector(GC) explicitly, therefore there is no way to determine when GC will remove memory from a paused activity. The test case at hand involves a ...

Tips for creating a plug-in plugin and applying the necessary parameters

(function( $ ){ var functions = { init : function( options ) { var settings = $.extend({ //Declaring default settings that can be overridden in the plugin call code: 7, listHe ...

How can we create a reusable dropdown list that appears when clicking on different elements?

Imagine having different sections of a webpage that, when clicked, reveal a dropdown list right below the selected link. I've noticed some websites accomplish this by actually having just one dropdown list defined in the DOM, which then appears below ...

I started off using Node.js with MongoDB, but now I want to switch to MySQL with Sequelize and implement async/await functions. However, I've run into a problem. Can

Can I use async await in JavaScript with Node.js Express and Sequelize to consult a table of products in an API? import { ProductoModel } from "../models/ProductoModel.js"; const listar = async (req,res) => { try { ...

Simple guide to maintaining the integrity of an absolute path within a script tag in index.html using Vite

When using Vite, absolute paths in the index.html file are automatically transformed based on the base configuration, which is quite convenient. For example, if my index.html looks like this: <script type="text/javascript" src="/config.j ...

In JavaScript, JSON data is parsed using a comma separator

Here is the format of my data: [{"QualID":1,"Qualification":"Van Driver"},{"QualID":3,"Qualification":"Safety Cert"},{"QualID":4,"Qualification":"Welder"}] I am look ...