How to save Blob in Ionic - pdf

I am new to ionic framework, actually I am getting byte array as response from back end service and converting it to blob. How can I save it to PDF in ionic?
var blob = new Blob([res], { type: 'application/pdf' });
Here res is the response (byte array) from the service.
Code
var blob = new Blob([res], { type: 'application/pdf' });
let fileName="Receipt.pdf";
let filePath = (this.platform.is('android')) ?
this.file.externalRootDirectory : this.file.cacheDirectory;
this.file.writeFile(filePath, fileName, blob, { replace: true }).then((fileEntry) => {
console.log("File created!");
this.fileOpener.open(fileEntry.toURL(), 'application/pdf')
.then(() => console.log('File is opened'))
.catch(err => console.error('Error openening file: ' + err));
})
.catch((err) => {
console.error("Error creating file: " + err);
throw err;
});
Thanks in advance.

In order to SAVE the PDF, you'll need to use some cordova plugins. Ionic has some nice wrappers around these here. Check out the File, File Transfer, and File Opener plugins.
Here's some example code you could use once you get these plugins incorporated into your project:
var blob = new Blob([res], { type: 'application/pdf' });
//Determine a native file path to save to
let filePath = (this.appConfig.isNativeAndroid) ? this.file.externalRootDirectory : this.file.cacheDirectory;
//Write the file
this.file.writeFile(filePath, fileName, blob, { replace: true }).then((fileEntry: FileEntry) => {
console.log("File created!");
//Open with File Opener plugin
this.fileOpener.open(fileEntry.toURL(), data.type)
.then(() => console.log('File is opened'))
.catch(err => console.error('Error openening file: ' + err));
})
.catch((err) => {
console.error("Error creating file: " + err);
throw err; //Rethrow - will be caught by caller
});

Related

How to create .DOC file witih expo-file-system?

I just created a similar question regarding promises...
But I'm having trouble saving .DOC files.
It comes corrupted when saving:
Could not get the file's extension.
and is being saved in:
file:///storage/emulated/0/DCIM/2021-09-01_5.doc
How to fix it?
data.map(async (index) => {
const date = new Date(index.synchronization)
const formattedDate = date.toISOString().split('T')[0];
const fileUri = `${FileSystem.documentDirectory}${formattedDate}.doc`;
await FileSystem.writeAsStringAsync(
fileUri,
"Hello World, i'am saving this file :)").then(response => console.log(response)).catch(error => console.log(error));
const { uri } = await MediaLibrary
.createAssetAsync(`${fileUri}`)
.then((response) => console.log(response))
.catch((error) => error);
console.log(uri)
await MediaLibrary.createAssetAsync("Downloads", uri).then(response => console.log(response)).catch(error => console.log(error.message));
});

How to upload image with express-fileupload from CKEditor5 properly?

My api as follows
router.post("/upload", async (req, res) => {
if (!req.files || Object.keys(req.files).length === 0) {
return res.status(400).send("No files were uploaded.");
}
console.log(req.files)
let file = req.files.upload;
let uploadPath = __dirname + "/../public/" + file.name;
file.mv(uploadPath, function (err) {
if (err) {
console.log(err)
return res.status(500).send(err)
}
res.sendStatus(200);
});
});
My react component
<CKEditor
editor={ClassicEditor}
config={{
ckfinder: {
uploadUrl: "/api/upload",
},
}}
data={props.state.tech.assess_info}
onChange={(event, editor) => {
..
}}
/>
Currently when I upload image from CKeditor, image is successfully uploaded(written to "public/{filename}" on server side). However CKEditor error popups and stating "cannot upload". I believe CKeditor is expecting specific response code, not just HTTP status 200. What do you guys think?
Ckeditor is expecting following response from API.
res.status(200).json({
uploaded: true,
url: `/uploads/${file.name}`,
});
Whole api code if anyone needs.
// Upload a file
router.post("/upload", async (req, res) => {
if (!req.files || Object.keys(req.files).length === 0) {
return res.status(400).send("No files were uploaded.");
}
let file = req.files.upload;
let uploadPath = __dirname + "/../public/uploads/" + file.name;
file.mv(uploadPath, function (err) {
if (err) return res.status(500).send(err);
res.status(200).json({
uploaded: true,
url: `/uploads/${file.name}`,
});
});
});

reaact-native get data from file from uri

This is a homework type question, please help as I'm new on react-native.
In react-native, I'm using react-native-document-picker, from the code in readme:
selectFiles = () => {
try {
DocumentPicker.pickMultiple({
type: [DocumentPicker.types.allFiles],
}).then((results) => {
console.log(result[0].uri);
}
});
} catch (err) { }
};
It provides me with an URI, how can convert that into path and read data of that file ?
Here is my solution :
var RNFS = require('react-native-fs');
...
RNFS.readFile(results[0].uri)
.then((file) => {
that.setState({code: file});
})
.catch((error) => console.log('err: ' + error));

How to save image to Document Directory from local file in react native?

I am new to react native, I want to save an image from local folder(like Module/assets/ImageName.png) in my project into Document Directory. I am using the 'react-native-fs' library for the same.
Code is below:
componentWillMount() {
var RNFS = require('react-native-fs');
var path = RNFS.DocumentDirectoryPath + '/ImageName.png';
// write the file
RNFS.writeFile(path, './Module/assets/ImageName.png', 'utf8') // what to use inplace of utf8?
.then((success) => {
console.log(path);
})
.catch((err) => {
console.log(err.message);
});
}
Please suggest how should I proceed?
Thanks.
For images included via Xcode asset catalogs use the image name without the extension:
var path = RNFS.DocumentDirectoryPath + '/ImageName.png';
RNFS.copyAssetsFileIOS('ImageName.png', path, 100, 100)
.then(results => {
console.log('Copy File', results);
})
.catch(err => {
console.log('Error copying file', err);
});

IONIC : pdf is not opening and downloading in IOS

I am creating pdf in IONIC 4. Following code is working on web and android but not on IOS. In IOS it is giving alert("Error creating file: " + err);
.catch(err => {
this.runloading = 'hide';
alert("Error creating file: " + err);
throw err;
});
if (this.platform.is("cordova")) {
this.pdfObj.getBuffer(buffer => {
var blob = new Blob([buffer], { type: "application/pdf" });
this.file
.writeFile(this.file.externalRootDirectory, "pro.pdf", blob, {
replace: true
})
.then(fileEntry => {
this.fileOpener
.open(
this.file.externalRootDirectory + "pro.pdf",
"application/pdf"
)
.catch(err => alert("Please install pdf viewer"));
this.runloading = 'hide';
})
.catch(err => {
this.runloading = 'hide';
alert("Error creating file: " + err);
throw err;
});
});
} else {
pdfmake.createPdf(docDefinition).open();
// this.pdfObj.download();
this.runloading = 'hide';
}
See this message below. There is a bug that prevents uniform experience for local file downloads on iOS.
Two choices:
1. Upload pdf to server and redownload it.
2. Await for iOS13
https://github.com/eligrey/FileSaver.js/issues/375#issuecomment-460318259