Ionic-native: File: checkFile(path, file) - FILE_NOT_FOUND

Created on 20 Jun 2017  Â·  11Comments  Â·  Source: ionic-team/ionic-native

I'm submitting a ...
[x] bug report

Current behavior:

As per the File.checkFile documentation, when using this function, the directory argument can be a string.

MyClass

  checkFileExistence(fileName: string) {
    return this.fileService.checkFile(this.fileService.photosDir, fileName).then(() => {
      console.log('File exists');
      return this.fileService.getFile(this.fileService.photosDir, fileName);
    }, (error) => {
      console.log('File does not exist');
      console.error(error);
      return this.fileService.copyFile(this.fileService.tempDir, fileName, 'photos');
    })
  }

FileService

  public checkFile(directory: string, file: string): Promise<boolean> {
    return this.file.checkFile(directory, file)
  }

And this is my output when first executing the Function which creates the File. Which is correct because the File doesn't exist, yet.

[Log] File does not exist (ion-dev.js, line 156)
[Error] FileError {code: 1, message: "NOT_FOUND_ERR"}
    (anonymous function) (ion-dev.js:156)
    (anonymous function) (main.js:150157)
    (anonymous function) (console-via-logger.js:173)
    (anonymous function) (main.js:69732)
    onInvoke (main.js:4406)
    run (polyfills.js:3:4147)
    (anonymous function) (polyfills.js:3:13735)
    onInvokeTask (main.js:4397)
    runTask (polyfills.js:3:4842)
    o (polyfills.js:3:1899)
    invoke (polyfills.js:3:10675)
    n (polyfills.js:2:28181)

However, when running it again, I get this:

[Log] File does not exist (ion-dev.js, line 156)
[Error] FileError {code: 1, message: "NOT_FOUND_ERR"}
    (anonymous function) (ion-dev.js:156)
    (anonymous function) (main.js:150144)
    (anonymous function) (console-via-logger.js:173)
    (anonymous function) (main.js:69719)
    onInvoke (main.js:4406)
    run (polyfills.js:3:4147)
    (anonymous function) (polyfills.js:3:13735)
    onInvokeTask (main.js:4397)
    runTask (polyfills.js:3:4842)
    o (polyfills.js:3:1899)
    invoke (polyfills.js:3:10675)
    n (polyfills.js:2:28181)
[Info] There was a problem while Copying the File (ion-dev.js, line 156)
[Error] FileError {code: 12, message: "PATH_EXISTS_ERR"}
    (anonymous function) (ion-dev.js:156)
    (anonymous function) (main.js:150144)
    (anonymous function) (console-via-logger.js:173)
    (anonymous function) (main.js:69696)
    onInvoke (main.js:4406)
    run (polyfills.js:3:4147)
    (anonymous function) (polyfills.js:3:13735)
    onInvokeTask (main.js:4397)
    runTask (polyfills.js:3:4842)
    o (polyfills.js:3:1899)
    invoke (polyfills.js:3:10675)
    n (polyfills.js:2:28181)
[Error] ERROR – Error: Uncaught (in promise): [object Object] — polyfills.js:3:13200
Error: Uncaught (in promise): [object Object] — polyfills.js:3:13200
    (anonymous function) (ion-dev.js:156)
    (anonymous function) (main.js:150144)
    defaultErrorLogger (main.js:1362)
    handleError (main.js:1422)
    handleError (main.js:147147)
    handleError (main.js:110120)
    next (main.js:5035:98)
    (anonymous function) (main.js:4108)
    __tryOrUnsub (main.js:15581)
    next (main.js:15530)
    _next (main.js:15472)
    next (main.js:15436)
    next (main.js:37090)
    emit (main.js:4094)
    triggerError (main.js:4466)
    onHandleError (main.js:4427)
    runGuarded (polyfills.js:3:4407)
    (anonymous function) (polyfills.js:3:14364)
    microtaskDrainDone (polyfills.js:3:14401)
    o (polyfills.js:3:2006)
    invoke (polyfills.js:3:10675)
    n (polyfills.js:2:28181)

Which is not correct because the File was previously created by the same function.

Expected behavior:

If I resolve the Directory in the checkFile function, like this:

Note: MyClass hasn't changed so I'm not going to put it again.

FileService

  public checkFile(directory: string, file: string): Promise<boolean> {
    return this.resolveDirectory(directory).then((resolvedDirectory: DirectoryEntry) => {
      return this.file.checkFile(resolvedDirectory.nativeURL, file)
    })
  }

This is my output.

...
[Log] File exists (ion-dev.js, line 156)
[Log] DirectoryEntry {isFile: false, isDirectory: true, name: "photos", fullPath: "/smartedi3/photos/", filesystem: FileSystem, …} (ion-dev.js, line 156)
[Log] cdv_photo_020.jpg (ion-dev.js, line 156)

I don't think this is necessarily a bug. However, the documentation should be changed to reflect this requirement as it's not that obvious that it needs to be a nativeURL string. Maybe instead of:

Param Type Details
path string

Base FileSystem. Please refer to the iOS and Android filesystems above

file string

Name of file to check

It should be:

Param Type Details
path string

Directory nativeURL, obtained by resolveDirectoryURL

file string

Name of file to check

improve docs

Most helpful comment

got this not found error because the passed file directory was not ending with /

All 11 comments

I am facing same issue, receiving this error [{"code":1,"message":"NOT_FOUND_ERR"}] instead of a boolean false when file doesnt exists. I tried resolvedDirectoryUrl but that didnt work for me either. Know any other alternatives?

@pooja-gaikwad15 Worked for me. Add some relevant code and I'll have a look.

var fileName = "data.json"; this.file.checkFile(this.file.applicationStorageDirectory, fileName) .then((result) => { console.log('file exists :' + result); },(error){ console.log('error : ' + JSON.stringify(error)});

Even tried checkFile function posted by you.. I am testing in android device.. [Iball-3G 1026-Q18 Android 4.4.2 API19]

I also have this issue. Also testing on android.

EDIT: I will add more updates as i test different workarounds.

I'm having the same issue here. Constantly getting {"code":1,"message":"NOT_FOUND_ERR"} on both Android and iOS devices

Error when selected photo from Android gallery.

My solution:
// destinationType: this.camera.DestinationType.FILE_URI

Temporary image name generated by gallery (error):
IMG-20180105-WA0000.jpg?1515167526856

Correct name for new image (success):
IMG-20180105-WA0000.jpg

copyFile(imageData){
    let path = this.filePathUrl(imageData)
    let fileName = this.filePathName(imageData)
    let newPath = this.storageDirectory+'galeria/'
    let newFileName = fileName

    console.log('***********************************************')
    console.log('imageData')
    console.log(imageData)

    console.log('path')
    console.log(path)

    console.log('fileName')
    console.log(fileName)

    console.log('newPath')
    console.log(newPath)

    console.log('newFileName')
    console.log(newFileName)

    console.log('***********************************************')
    console.log('\n\n')

    this.file.copyFile(path, fileName, newPath, newFileName).then(data => {
      var itemSrc = data.nativeURL.replace(/^file:\/\//, '');
      this.imageFileName = itemSrc;
    }, err => {
      console.log(JSON.stringify(err))
    })
  }

filePathName(imageData){
    if(this.platform.is('android') && this.sourceType == 'galeria') {
      var nome = imageData.substr(imageData.lastIndexOf('/') + 1);
      nome = nome.split('?')
      return nome[0]
    }    
    return imageData.substr(imageData.lastIndexOf('/') + 1);
}
filePathUrl(imageData){
    return imageData.replace(this.filePathName(imageData), '');
}

I hope it works for you.

@pooja-gaikwad15, checkFile and checkDirectory never return false! The API is confusing. They return (a Promise returning) true if the thing exists, and an error (rejected Promise) otherwise.

got this not found error because the passed file directory was not ending with /

Adding '/' works for me!

Hi guys,
After so much trying, I found this solution to store images

let UUID = 'empleado-' + (new Date().getTime()).toString(16);

` // imagen = data:image/jpeg;base64,/9j/4........
let realData = imagen.split(",")[1];
let blob = this.b64toBlob(realData, 'image/jpeg');

this.file.checkDir(this.file.externalApplicationStorageDirectory, 'DirectorioFotos')
    .then(_ => {
      this.file.writeFile(this.file.externalApplicationStorageDirectory + 'DirectorioFotos/', UUID + '.jpg', blob).then(response => {
        // ACTION
      }).catch(err => {
        // ACTION
      })
    })
    .catch(err => {
      this.file.createDir(this.file.externalApplicationStorageDirectory, 'DirectorioFotos', false).then(result => {
        this.file.writeFile(this.file.externalApplicationStorageDirectory + 'DirectorioFotos/', UUID + '.jpg', blob).then(response => {
          // ACTION
        }).catch(err => {
          // ACTION
        })
      })
    });`

`b64toBlob(b64Data, contentType) {
contentType = contentType || '';
var sliceSize = 512;
var byteCharacters = atob(b64Data);
var byteArrays = [];

for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
  var slice = byteCharacters.slice(offset, offset + sliceSize);

  var byteNumbers = new Array(slice.length);
  for (var i = 0; i < slice.length; i++) {
    byteNumbers[i] = slice.charCodeAt(i);
  }

  var byteArray = new Uint8Array(byteNumbers);

  byteArrays.push(byteArray);
}

var blob = new Blob(byteArrays, {type: contentType});
return blob;

}`

I hope someone is helpful

same issue

Was this page helpful?
0 / 5 - 0 ratings

Related issues

jgw96 picture jgw96  Â·  3Comments

shaliko picture shaliko  Â·  3Comments

lycwed picture lycwed  Â·  4Comments

rajanshahsa picture rajanshahsa  Â·  3Comments

mateo666 picture mateo666  Â·  3Comments