cordovaangularionic2cordova-plugins

FileTransfer returns error with all properties `null`


In my Ionic 2 application I'm taking a picture with cordova-plugin-camera where I retrieve the picture by FILE_URL (local device's image location) which works well.

This gives me the URL like so when taking a picture with the camera: file:///storage/emulated/0/Android/....../1234.jpg

And like this when selecting an image from the gallery: content://com.android.providers.media.documents/document/image%232312

Now I'm trying to upload this image using cordova-plugin-file-transfer.

My upload function is like the following:

upload(){
    let options: FileUploadOptions = {
        fileKey: 'file',
        fileName: 'my_image.jpg',
        headers: {'X-CSRF-Token': localStorage.getItem('u:token')}
    }
    alert(this.imageSrc);
    this.fileTransfer.upload(this.imageSrc, encodeURI(this.API_URL), options, true)
        .then(data => {
            alert("d:"+JSON.stringify(data));
        }, err => {
            alert("E:"+JSON.stringify(err));
        });
}

But I receive an error object holding the following

{
  "code" : "null",
  "source" : "null",
  "target" : "null",
  "http_status" : "null",
  "body" : "null",
  "exception" : "null"
}

Note: no additional erros are being throwm


Solution

  • Alright so the problem was that the Gallery returned a contentURI but not a fileURI which is needed by the FileTransfer. The problem occured both on content: and /storage/ URIs.

    I used a bad practice workaround but since it still isn't fixed, I'll share it.

    I fixed it by adding the FilePath(cordova-plugin-filepath).

    Below function uses the storage and content URI's and converts them to a filepath.

    (Image source global in my case)

    convertIfAndroidGalleryImage() {
            // android bug, sometimes returns an image starting with content: or /storage/ which won't upload. 
            // Convert to a filepath.
            if(this.imageSrc.startsWith('content') || this.imageSrc.startsWith('/storage/')) {
                if(this.imageSrc.startsWith('/storage/')) {
                    this.imageSrc = 'file://'+this.imageSrc;
                }
                this.filePath.resolveNativePath(this.imageSrc).then(filePath => {
                    this.imageSrc = filePath;
    
                }).catch(err => { console.log("error occurred"); });
            }
        }