How to use a downloaded file (ionic 2) - android

I am making an app for android/ios using ionic 2. I want to download a JSON file from a specific url on the net and then use it inside my app. This code is how I download:
const imageLocation = `my url for .json file`;
if (this.platform.is('ios')) {
targetPath = cordova.file.applicationStorageDirectory + "data.json";
}
else if(this.platform.is('android')) {
targetPath = cordova.file.dataDirectory + "data.json";
console.log(cordova.file.dataDirectory + "data.json");
}
fileTransfer.download(imageLocation, targetPath).then((entry) => {
const alertSuccess = this.alertCtrl.create({
title: `Download Succeeded!`,
subTitle: `file was successfully downloaded to: ${entry.toURL()}`,
buttons: ['Ok']
});
alertSuccess.present();
}, (error) => {....
I want to use this downloaded file in my provider to fetch data from it. How can I do that?

If you want to save the file, you can choose among many options:
Save it in localStorage
Save it in a SQLite database
Use WebStorage
Use new technologies like CouchDB, etc.
Alternatively, if the file is not very large, feel free to simply store it in a local variable of the provider, i.e. just add a setter method in your provider and pass the JSON object to it, so that it stores it in your provider. Note that in this case the data will be lost when the app is restarted.

Related

How to export data into a specific extension ? like PDF

I'm trying to program an app that let users write their novels or notes with fun features like listening to piano and raining sounds while writing...etc. Everything works fine and great but the problem is how can i turn those novels to PDF? ... I store everything as a "String" data type...ofc the user want to save his work which obviously I can do (Local storage or firebase) however i don't know about exporting data as a specific extension. how can I export the data as a PDF file if the user wanted to do that? is there a general way to do it?
One possible solution can be pdf Flutter plugin. You can create and save a pdf file from strings. I tried this sample code and pdf is created:
//get the directory to save pdf file
late Directory? directory;
if (Platform.isIOS) {
directory = await getApplicationDocumentsDirectory();
} else {
directory = await getExternalStorageDirectory();
}
var path = directory?.path;
//create pdf file
final pdf = pw.Document();
pdf.addPage(
pw.Page(
build: (pw.Context context) => pw.Center(
child: pw.Text('Hello World!'),
),
),
);
//save pdf file
await File('$path/test.pdf').writeAsBytes(await pdf.save());
You can use path_provider Flutter plugin to get the directory location

Getting write access to a directory path in flutter API 30 and above

I want to know how to get write access to a directory path in flutter on API 30 and above. Currently, I cannot find a working complete solution to it anywhere on the internet.
And it would be very grateful if anyone could answer this completely in a detailed way or provide a working sample project.
Note: I know this is not accurately an answer to my question that's why not marked as an answer but this could be useful for those who wanted the "write access" for saving a file in a user-defined location with the native save dialog.
Add flutter_file_dialog plugin in pubspec.yaml. (Version 2.3.0 used in this answer)
Create a function like this.
Future<String?> saveFileInUserDescribedLocation() async {
//Create parameters for save file dialog
//Saving a file through Uint8List data
final params = SaveFileDialogParams(
mimeTypesFilter: ["application/pdf"],
data: Uint8List.fromList(bytes),
fileName: 'Test.pdf');
//You can also use a source file path to save a file through its path like this
//final params = SaveFileDialogParams(
// sourceFilePath: tempPdfPath, mimeTypesFilter: ["application/pdf"]);
//Now provide parameters and save the file.
//It will return the file path chosen by the user to save the file after saving the file.
final filePath = await FlutterFileDialog.saveFile(params: params);
debugPrint("Save filePath: $filePath");
return filePath;
}
Then execute the saveFileInUserDescribedLocation() function. It will provide a native dialog to the user asking the user to choose a location to save and then saves the file.
ElevatedButton(
onPressed: () { await saveFileInUserDescribedLocation(); },
child: const Text("Save File")
)

Get the array of filenames stored in document directory in React Native

CASE
I have downloaded audio files to my document directory under the folder named /tracks/ as :
RNFetchBlob.fs.dirs.DocumentDir + '/tracks/'
No doubt I can read each audio by their name as :
RNFetchBlob.fs.dirs.DocumentDir + '/tracks/' + 'audio1.mp3'
QUESTION:
I want to get the list of all the audios.
I can see in File Access API , we can read file but I am unable to find how to get the list of audio files from the folder '/tracks/'.
I just want to have an array of filenames in that directory.
File Access API link :
https://github.com/wkh237/react-native-fetch-blob/wiki/File-System-Access-API#dirs
P.S: I didn't want to go for other file access plugins.
I don't know if I have to search other libraries for file listing .
UPDATE
With the following code:
var TRACK_FOLDER = RNFetchBlob.fs.dirs.DocumentDir + '/tracks/';
console.log('Files LIST in Tracks Folder = ', RNFetchBlob.fs.ls(TRACK_FOLDER));
OUTPUT IS :
I think I'm getting close but's output seems difficult to parse.
:(
FINALLY:(this is the way how it is done)
var TRACK_FOLDER = RNFetchBlob.fs.dirs.DocumentDir + '/tracks/';
console.log('Files list in TRACK_FOLDER = ', RNFetchBlob.fs.ls(TRACK_FOLDER));
RNFetchBlob.fs.ls(TRACK_FOLDER)
.then( (files) =>{
console.log(files.length);
console.log(files);
console.log(files[0]);
})
OUTPUT:
Hope this helps somebody out there.
RNFetchBlob.fs.ls returns a promise.
So you can either access it with using .then/.catch
RNFetchBlob.fs.ls(TRACK_FOLDER).then(files => {
console.log(files);
}).catch(error => console.log(error))
or you can use async/await
try {
let files = await RNFetchBlob.fs.ls(TRACK_FOLDER);
console.log(files);
} catch (error) {
console.log(error);
}
You can read more about RNFetchBlob.fs.ls here. Also note that the repository for RNFetchBlob has moved to here https://github.com/joltup/rn-fetch-blob
I used lstat which returns all files include following:
{
filename: "RNPM_2238640396305543067.png"
lastModified: "1632219571000"
path: "/data/user/0/com.test.app/cache/RNPM_2238640396305543067.png"
size: "21059"
type: "file"
}

Is there any way to prefetch or cache audio in React Native?

Is there any method to prefetch audio in React Native or is there any library that allows me to do so ?
With lack of information, I believe you are asking if you can download audio with react native?
You can use something like https://www.npmjs.com/package/rn-fetch-blob
This will allow you to save a stream to phone storage, give you a path to the file on the phone, then you can save that to reuse at a later time.
An example from their docs.
RNFetchBlob.config({
// add this option that makes response data to be stored as a file,
// this is much more performant.
fileCache : true,
})
.fetch('GET', 'http://www.example.com/file/example.zip', {
//some headers ..
})
.then((res) => {
// the temp file path
console.log('The file saved to ', res.path())
})

Downloading a pdf blob to device in Cordova Android App

I am working on a program where I want to save a pdf blob in a android device.
This is server side code inside a callback which receives pdf data as 'result'.
var file = new Blob([result.data], {
type: 'application/pdf;charset=utf-8;'
});
return file;
});
At client side, the following code works in chrome debugging browser and pdf is successfully downloaded. However on device I get the following error :
11-18 18:13:27.255 10504-10707/? D/FileTransfer: download blob:file:///e9088aac-8525-4071-9280-164a6e15c22e to file:///storage/emulated/0/Download/loanContract_11-10-2016_9-29-59-715.pdf
11-18 18:13:27.255 10504-10707/? E/FileTransfer: Unsupported URI: blob:file:///e9088aac-8525-4071-9280-164a6e15c22e
Here the data in window.URL.createObjectURL(data) is the file blob returned by server. Phonegap/Cordova 3.6 - Download of file through blob:file didnt help me in solving the problem.
var fileURL = window.URL.createObjectURL(data);
$scope.content = data;
a.href = fileURL;
a.download = fileName;
a.click();
console.log("Inside parent function");
$scope.fileName = fileName;
window.resolveLocalFileSystemURL(cordova.file.externalRootDirectory, function (dirEntry) {
download($scope.fileURL, dirEntry.toURL()+'Download/'+ $scope.fileName) ;
}, function () {} );
var download = function ( uri, fileURL) {
$cordovaFileTransfer.download(
uri,
fileURL,
function (success) {
console.log(success);
},
function (err) {
console.log(err);
}, true)
};
If i give a url which sends a pdf file as HTTP response and I provide the API's URL as the parameter uri to cordovaFileTransfer.download, then the pdf gets saved.
Kindly help me saving this bob as a pdf on the device.
First, get the file by requesting the file system and then download it from your server with fileTransfer.download(). After completing the download call the FileOpener (which will open a pop up where to choose from apps like Adobe Reader). Note: Make sure to include the FileTransfer feature via CLI/Terminal:
cordova plugin add cordova-plugin-file --save
Navigate to your project folder
Open CLI/Terminal and type in:
cordova plugin add
https://github.com/don/FileOpener.git
After successful download and storage of your file on the device (see
above) you open it with:
window.plugins.fileOpener.open("file:///sdcard/Android/data/com.example.application/document.doc")
or the appropriate path on iOS.

Categories

Resources