Hi folks,
I have to download pdf file based on data coming from API, thus for this I am using ionic native file plugin for creating the file and saving it in the device storage.
Following is the process
- Receives data as octect-stream from API
- Create blobs
- By using writeFile() of file plugin I store it in the device storage.
The pdf file gets created successfully, with correct size and format, but when I open it, file is empty as in no data is displayed.
Can anyone shed some light on this.
Following is the code
import { File } from '@ionic-native/file/ngx';
downloadPDF() {
if (this.platform.is('android')) {
this.androidPermissions.checkPermission(this.androidPermissions.PERMISSION.WRITE_EXTERNAL_STORAGE)
.then(status => {
if (status.hasPermission) {
this.downloadFile();
}
else {
this.androidPermissions.requestPermission(this.androidPermissions.PERMISSION.WRITE_EXTERNAL_STORAGE)
.then(status => {
if (status.hasPermission) {
this.downloadFile();
}
})
}
})
} else {
this.downloadFile();
}
}
downloadFile() {
this.apiService.postRequest(URL, "").subscribe(resp => {
let blobData = new Blob([resp._body], { type: "application/pdf" });
console.log("blobData", blobData);
let fileName ="myPdf.pdf";
this.writeImageFile(blobData, 'Download', fileName, true);
})
}
writeImageFile(imageData, newdirectory, fileName, isBlob?) {
console.log("inside write file fucntion");
let rootdirectory = this.file.externalApplicationStorageDirectory;
console.log("rootdirectory", rootdirectory)
console.log("new directory", rootdirectory + newdirectory)//imageobj["entityGuid"]
let imagetowrite: any;
if (isBlob)
imagetowrite = imageData;
console.log("imagetowrite", imagetowrite);
return this.file.createDir(rootdirectory, newdirectory, false).then(newdir => {
console.log(newdir)
console.log(fileName)
return this.file.writeFile(rootdirectory + newdirectory, fileName, imagetowrite, { replace: true }).then(filedata => {
console.log(filedata)
console.log(rootdirectory + newdirectory + "/" + fileName)
return filedata
// this.readFile()
}).catch(err1 => {
console.log("directory does not exist - error")
console.log(err1)
})
}).catch(err => {
console.log(err)
console.log(fileName)
return this.file.writeFile(rootdirectory + newdirectory, fileName, imagetowrite, { replace: true }).then(filedata => {
console.log(filedata)
return filedata
}).catch(err1 => {
console.log("directory exist - error")
console.log(err1)
})
})
}