Download file or image from the server

i want to download image file and other file from the server, i have used fileTransfer plugin but the problem is this plugin assumes that the response will be always a file, when i’m requesting for download if the authentication token is expired then the response is in json string but this plugin take response as a file and store that response in to file. my code is as below

const fileTransfer: FileTransferObject = this.transfer.create();

let fileTransferDir = this.file.dataDirectory;
let classname = nodeId + '/'
var fileURL = fileTransferDir + classname + fileName + '.png';

let options = {
  headers: {
    'token': tkn,
    'type': "image",
    'file': fileName
  }

}
console.log("headers ................. " + JSON.stringify(options));

return new Promise((resolve, reject) => {

  fileTransfer.download(this.apiUrl + '/getFile', fileURL, true, options)
    .then((data) => {

      resolve(data);
    }, (err) => {
      console.log(err);
    });

});

and the https://github.com/apache/cordova-plugin-file-transfer#deprecated says that this plugin is deprecated then what should i use to get response as a json string or a file?

or is there any way to read response header content-type from this plugin?

use file-transfer

1 Like

I would just go with HttpClient and the ordinary Cordova File plugin.

that’s what i’m using, but the problem is when the response is in Json string instead of file then the response in written in that file and this plugin assume that the response in always file. if its not file then if still showing positive response like…

{“isFile”:true,“isDirectory”:false,“name”:“42551909ce419cc21ddfbffb02a1ecc8.png”,“fullPath”:"/25079027156910150_bc/42551909ce419cc21ddfbffb02a1ecc8.png",“filesystem”:"<FileSystem: files>",“nativeURL”:“file:///data/user/0/com.test.test/files/25079027156910150_bc/42551909ce419cc21ddfbffb02a1ecc8.png”}

means file is downloaded but this file contains response from the server like

{ response : ‘token expired’}

can you give me any example?

Using httpclient and file plugin means httpclient make request to donwload file and get blob object and file.writeFile to create a new file. Is it correct?

But this way I found httpclient download will cause a temp cache of the downloaded file. For example, httpclient dowload a 5MB file using httpclient and the storage volume of app increase 5MB. And then doing file.writeFile will increase another 5MB because the cache file still remain. If I need to download a lot of files with large data, it may cause problem. Do you have any idea to solve this to avoid increasing double size of data?

I am not familiar with the caching issue that you mention.

However, I faced a similar situation and used a class with several properties, one of which was the file to transfer.

I have heard interfaces are what is to be used vs. a class. I have not researched that topic enough.