Delete file from file system in ionic 4 - file

I am working with one application in which I am creating offline PDF and save them in file system.
Now the problem is when I delete the particular record I need to delete the PDF from file system I go through the file plugin but couldn't find any method related to that. I am using ionic 4 here are some peace of code.
if (this.plt.is('cordova')) {
this.pdfObj.getBuffer((buffer) => {
const blob = new Blob([buffer], { type: 'application/pdf' });
// Save the PDF to the data Directory of our App
this.file.writeFile(this.file.externalRootDirectory + '/Downloads/', 'ACCSYS-' +
this.randomString(4) + '-' + encodeURI(this.headerData.title) + '.pdf', blob, { replace: true }).then(fileEntry => {
// Open the PDf with the correct OS tools
setTimeout(() => {
this.hideLoader();
this.fileOpener.open(fileEntry.nativeURL, 'application/pdf');
this.pdfObj = null;
}, 1000);
});
});
} else {
setTimeout(() => {
this.hideLoader();
this.pdfObj.download();
this.pdfObj = null;
}, 500);
}
Assume I store the nativeURL in localstorage.
any idea how to delete the file ??

If you already have a fileEntry object you can use the remove() method to delete the file like this:
fileEntry.remove(function() {
// if the file has been successfully removed
}, function(error) {
// if there was an error removing the file
}, function() {
// if the file does not exist
});
See these links for more documentation and examples.

here is the perfect way to do it ( define window on the top of ts file )
delete() {
// this.fileHelper.removeFile();
const fileToRemove = this.remoteURL; // Change this with your file path
window.resolveLocalFileSystemURL( fileToRemove, (dirEntry) => {
dirEntry.remove(this.successHandler, this.errorHandler);
});
}
successHandler() {
console.log('Directory deleted successfully');
}
errorHandler() {
console.log('There is some error while deleting directory')
}

Related

deleting files from firebase storage

So I'm allowing user's upload certain images in the storage of firebase, and each file is named after their user id. So when a user uploads an image, I get a url that for that file
https://firebasestorage.googleapis.com/v0/b/jobify-a7a4a.appspot.com/o/CZx5biMydzQAOx4T8WXJU5jt2852%2Fimages%2Fdreamy-waterfall-4k-sc.jpg?alt=media&token=8e4d60ed-e956-4f71-80d1-58755fe94dbe
And so when a user changes the uploaded image, I'd like to delete the previously updated image from the storage.
I've seen how they do it in the docs, but that requires the file name which I don't have access to.
This is the code when a user uploads an image
function uploadImg(e) {
const file = e.target.files[0];
if (file && file.size < 30000000) {
var storageRef = firebase
.storage()
.ref(`${user.uid}/images`)
.child(file.name);
const task = storageRef.put(file);
task.on(
"state_changes",
function progress(snap) {
setLoading(true);
const percentage = (snap.bytesTransferred / snap.totalBytes) * 100;
loadingref.current.style.height = percentage + "%";
},
function error() {
setNotifibool(true);
setNotifi({
text: "Try Again!",
icon: "fal fa-exclamation-circle"
});
},
function complete() {
setLoading(false);
storageRef.getDownloadURL().then((url) => {
setState(url);
});
setNotifi({
text: "Image Uploaded!",
icon: "fal fa-check-circle"
});
}
);
} else {
window.alert("too big");
}
}
You can translate the download URL you have back to a reference by calling firebase.storage().refFromUrl(downloadUrl). Then your can delete the file by calling delete on that reference.

Uploading file using PERN stack

I'm using PERN stack and while uploading the files in the UI except the xlsx file each files are getting uploaded. I have no what's going wrong. I referred a lot of things but none of them are targeting to what I'm looking for.
I'm even providing the code.
const data = new FormData();
console.log("state in general =====", this.state.selectedFile);
if (selectedFile && selectedFile.length > 0) {
for (var x = 0; x < selectedFile.length; x++) {
data.append("file", selectedFile[x]);
data.append("filename[]", this.state.selectedFile[x].name);
}
console.log("uploaded file data", data); // this data variable is my payload in the api.
}
Backend error :
Backend code :
await Promise.all(
req.files.map(async file => {
let document = await someClass.select("tableName", {
//few parameters.
});
console.log(document);
if (document.length === 0) {
// if the file doesn't exists then only upload the new file.
insert.then(doc => {
const result = {
status: "ok",
filename: doc.filename,
message: "Upload Successfully!",
};
messages.push(result);
})
.catch(err => {
console.log("error in uploading file----------", err);
const result = {
status: "fail",
filename: file.originalname,
message: "Can NOT upload Successfully",
};
sendResponse(res, "Files Found", result);
});
} else {
// sendResponse(res, "Files found", document);
}
})
);
Any help will be appreciated.

Nativescript Class constructor Observable cannot be invoked without 'new'

I'm trying to upload a multipart form in nativescript and I'm using http-background. I keep getting the error Class constructor Observable cannot be invoked without 'new'. I've tried changing the compilerOptions target to es5 and es2017, but nothing changed.
Here's all my code from the component.
onSave(){
console.log("clicked")
this.proccessImageUpload(this.file);
}
public onSelectSingleTap() {
this.isSingleMode = true;
let context = imagepicker.create({
mode: "single"
});
this.startSelection(context);
}
private startSelection(context) {
let that = this;
context
.authorize()
.then(() => {
that.imageAssets = [];
that.imageSrc = null;
return context.present();
})
.then((selection) => {
console.log("Selection done: " + JSON.stringify(selection));
this.file = selection[0]._android;
that.imageSrc = that.isSingleMode && selection.length > 0 ? selection[0] : null;
// set the images to be loaded from the assets with optimal sizes (optimize memory usage)
selection.forEach(function (element) {
element.options.width = that.isSingleMode ? that.previewSize : that.thumbSize;
element.options.height = that.isSingleMode ? that.previewSize : that.thumbSize;
});
that.imageAssets = selection;
}).catch(function (e) {
console.log(e);
});
}
// proccess image function
proccessImageUpload(fileUri) {
var backgroundHttp = require("nativescript-background-http");
return new Promise((resolve, reject) => {
// body...
var request = {
url: 'http://192.168.0.2:4000/api/posts',
method: "POST",
headers: {
"Content-Type": "application/octet-stream",
"user_id": "<user_id>"
},
description: 'Uploading profile image..',
androidAutoDeleteAfterUpload: false,
androidNotificationTitle: 'Profile image'
}
var params = [
{ name: "title", value: "test" },
{ name: "content", value: "test" },
{ name: "fileToUpload", filename: fileUri, mimeType: "image/jpeg" }
];
var backgroundSession = backgroundHttp.session('image-upload');
var task = backgroundSession.uploadFile(fileUri, request);
task.on("progress", (e) => {
// console log data
console.log(`uploading... ${e.currentBytes} / ${e.totalBytes}`);
});
task.on("error", (e) => {
// console log data
console.log(`Error processing upload ${e.responseCode} code.`);
reject(`Error uploading image!`);
});
task.on("responded", (e) => {
// console log data
console.log(`received ${e.responseCode} code. Server sent: ${e.data}`);
// var uploaded_response = JSON.parse(e.data);
});
task.on("complete", (e) => {
// console log data
console.log(`upload complete!`);
console.log(`received ${e.responseCode} code`);
// console.log(e.data);
})
resolve(task);
});
}
I know the issue is coming from this line.
var task = backgroundSession.uploadFile(fileUri, request);
Any help would be greatly appreciated!
You use old version if nativescript-background-http plugin
You have to install latest version
tns plugin add #nativescript/background-http
I was able to get this working by installing tns version 6.
I had exactly the same problem. I got this from slack.com, compliments Chris Vietor
"tns plugin add nativescript-background-http" works with nativescript 6.
"tns plugin add #nativescript/background-http" works with nativescript 7.

IONIC 3 - I want to get file path of the pdf when select from file manager

Here i am posting my code of selecting PDF from file manager. i need to get file path of selected PDF. how can i get it?
.html
<input type="file" (change)="selectPDF($event)" class="file-input upload-items" name='company_pdf' style="opacity: 0"
id="company_pdf" #fileInp>
.ts
selectPDF(fileInput: any) {
if (fileInput.target.files[0].type == 'application/pdf') {
console.log(fileInput.target.files)
this.PDFfiles.push(fileInput.target.files[0]);
if (this.PDFfiles.length > 4) {
this.disablePdfUplaod = true;
}
//this.PDFfile = fileInput.target.files[0];
} else {
this.shared.showToast('Please select PDF')
}
}
Here you can find both android and iOS platform answer. How to pick pdf document and view that document.
.html
<input (click)="openFile()" class="file-input upload-items" name='company_pdf' style="opacity: 0"
id="company_pdf" >
.ts
openFile() {
if (this.platform.is('android')) {
this.fileChooser.open()
.then(
uri => {
this.filePath.resolveNativePath(uri)
.then(url => {
console.log(url)
// url is path of selected file
var fileName = url.substring(url.lastIndexOf("/") + 1)
console.log(fileName)
// fileName is selected file name
})
.catch(err => console.log(err));
}
)
.catch(error => {
console.log(error)
});
} else {
this.docPicker.getFile('pdf')
.then(uri => {
console.log(uri)
var fileName = uri.substring(uri.lastIndexOf("/") + 1)
})
.catch(e => console.log(e));
}
}
Hope it will helps you.
You can try Ionic FileOpener
this.fileOpener
.open(filePath, fileExtension)
.then(() => {
return true
});
the best approach would be Document Viewer
Document Viewer
This plugin offers a slim API to view PDF files which are either stored in the apps assets folder (/www/*) or in any other file system directory available via the cordova file plugin.
$ ionic cordova plugin add cordova-plugin-document-viewer
$ npm install --save #ionic-native/document-viewer
import { DocumentViewer } from '#ionic-native/document-viewer';
constructor(private document: DocumentViewer) { }
const options: DocumentViewerOptions = {
title: 'My PDF'
}
this.document.viewDocument('assets/myFile.pdf', 'application/pdf', options)
if u are choosing from file manager do some like this and open the pdf from my other answer
this.fileChooser.open()
.then(
uri => {
this.filePath.resolveNativePath(uri)
.then(file => {
this.fileDir = file;
this.fileName = file.substring(file.lastIndexOf("/") + 1);
// open the pdf
})
.catch(err => console.log(err));
}
)
.catch(error => {
this.showError(error);
});

Downloading from S3 in node and opening in a new window

My Angular 1 application saves files to S3 and allows for a wide variety of files types.
When I retrieve the objects I use the following code:
export function show(req, res) {
const s3 = new aws.S3();
const s3Params = {
Bucket: S3_BUCKET,
Key: req.query.key + ''
};
res.attachment(req.query.key + '');
var fileStream = s3.getObject(s3Params).createReadStream();
fileStream.pipe(res);
}
I would like to open the received file on the client in a new window (just like on the AWS console) but I can't figure out how to go about it.
For example on the client side does not work at all:
.then(
(data) => {
var file = new Blob([data], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
window.open(fileURL);
}
)
I really don't understand how the concept of data streams works.
If you don't have to download pdf, you may open it directly from s3.
s3client.getResourceUrl("your-bucket", "some-path/some-key.jpg");
This will return you url to the file.
So you need code like:
export function show(req, res) {
this.s3client = new aws.S3({
accessKeyId: options.accessKeyId,
secretAccessKey: options.secretAccessKey,
region: options.region
})
let resourceUrl = s3client.getResourceUrl(S3_BUCKET, req.query.key + '');
window.open(resourceUrl, '_blank');
}
I'm sorry, can't test it right now, but try. Should work.
All I had to do was get a signedUrl for the resource for this to work much simpler than what I was trying to do.
export function show(req, res) {
const s3 = new aws.S3();
const s3Params = {
Bucket: S3_BUCKET,
Key: req.query.key + ''
};
s3.getSignedUrl('getObject', s3Params, (err, data) => {
if (err) {
console.log(err);
return res.end();
}
const returnData = {
signedRequest: data,
};
res.write(JSON.stringify(returnData));
res.end();
});
}
and on the client all I have to do is open the link in a new tab:
openDoc(doc) {
this.$http()
.then(
(data) => {
this.$window.open(data.data.signedRequest, '_blank')
}
)
.catch(
(err) => {
this.Notification.error('failed to download attachment');
}
)
}

Resources