How to Push Realm File to Internal Storage in React Native from Application - react-native

I am working on a application which ships whole database file shared within React Native Code to user internal storage. For pushing file to internal storage on Android I am using Realm the code we have done work correctly for iOS but for Android I am getting file not found (aka. The Realm is not pushing an file to Internal Storage Android)
Here what I done until now
export default new Realm({
path:Platform.OS === 'ios'
? RNFS.MainBundlePath +'/www/RippleEffect.realm'
: RNFS.DocumentDirectoryPath +'/RippleEffect.realm',
schema: [apply_it,
case_study,
got_it,
got_it_2,
got_it_2_question,
got_it_2_question_answer,
got_it_question,
got_it_question_answer,
howto,
howto_screens,
info,
info_screens,
model,
profile,
profile_result,
profile_statements,
related_topic,
special_assets_table_teens,
topic_audio,
topic_equivalence,
topics,
true_story,
your_mind,
],
readOnly: true
});
Use this two dependency
import Realm from 'realm';
import RNFS from 'react-native-fs'
And In App Class
const App = () => {
Realm.copyBundledRealmFiles();
return (
<App/>
);
};

For those who are working React Native with Realm DB
I solve this issue by pushing realm file from assets folder to internal folder(user mobile ) and thus I was able to read an write about database.
File dbDirectory = new File(MainApplication.getFileDirectory() + "/db");
/**
* Check for database
* directory
*/
if(!dbDirectory.exists()){
if(dbDirectory.mkdirs()){
moveDBFileToCard("database.realm");
}
}
private void moveDBFileToCard(String databaseFileName) {
try{
AssetManager assetsManagerFiles = getAssets();
/**
* Intialize Stream
*/
InputStream inputStream;
OutputStream outputStream;
inputStream = assetsManagerFiles.open(databaseFileName);
System.out.println("File Path = " + MainApplication.getFileDirectory() + "/db" + "/" + databaseFileName);
File fileDB = new File(MainApplication.getFileDirectory() + "/db" + "/" + databaseFileName);
if (fileDB.exists()) {
fileDB.delete();
}
outputStream = new FileOutputStream(MainApplication.getFileDirectory() + "/db" + "/" + databaseFileName);
byte[] buffer = new byte[1024];
int read;
while ((read = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, read);
}
inputStream.close();
outputStream.flush();
outputStream.close();
}catch (IOException io){
io.printStackTrace();
}
}
And also removed
readOnly: true from file as it was giving issue to filter quesry on 0.60 version

Related

How to download files through development vscode extension on code-server?

I wrote a vscode extension. Now you want to download a file in the vscode working directory by developing extensions. But no files were obtained through vscode vscode.Uri.file.
const downloadPanel = vscode.window.createWebviewPanel(
"view",
"下载",
vscode.ViewColumn.Two,
{
enableScripts: true,
retainContextWhenHidden: true,
}
)
if (vscode.workspace.workspaceFolders === undefined) {
throw new Error("not found!");
}
const filePath = vscode.workspace.workspaceFolders[0].uri.fsPath;
let downloadContent = vscode.commands.registerCommand('download.click', () => {
console.log("filePath = " + filePath);
const onDiskPath = vscode.Uri.file(
path.join(context.extensionPath, "resources","blockchain.svg")
);
// And get the special URI to use with the webview
const catGifSrc = panel.webview.asWebviewUri(onDiskPath) + "";
getWebviewContent(catGifSrc);
function getWebviewContent(_src: string) {
return '<html><head><script></script></script></head><body><div>download</div></body></html>';
}
When clicking the link, the file is not found! Currently, only nginx proxy can be used for full path downloading. Is there any other plan or solution?

Sending audio file created with RecordRTC to my server

I am new to working with Javascript, PHP, and with servers generally. I am working on a web page that will record audio from the user and save it to my server, using RecordRTC. I'm a bit confused about the XMLHttpRequest portion - how do I alter the following code to send to my server instead of the webrtc server?
function uploadToServer(recordRTC, callback) {
var blob = recordRTC instanceof Blob ? recordRTC : recordRTC.blob;
var fileType = blob.type.split('/')[0] || 'audio';
var fileName = (Math.random() * 1000).toString().replace('.', '');
if (fileType === 'audio') {
fileName += '.' + (!!navigator.mozGetUserMedia ? 'ogg' : 'wav');
} else {
fileName += '.webm';
}
// create FormData
var formData = new FormData();
formData.append(fileType + '-filename', fileName);
formData.append(fileType + '-blob', blob);
callback('Uploading ' + fileType + ' recording to server.');
makeXMLHttpRequest('https://webrtcweb.com/RecordRTC/', formData, function(progress) {
if (progress !== 'upload-ended') {
callback(progress);
return;
}
var initialURL = 'https://webrtcweb.com/RecordRTC/uploads/';
callback('ended', initialURL + fileName);
listOfFilesUploaded.push(initialURL + fileName);
});
}
Via my web hosting provider, I'm using an Apache server, phpMyAdmin, and a mySQL database. Do I just replace
makeXMLHttpRequest(https://webrtcweb.com/RecordRTC/
with "https://mywebsite.com" and replace
var initialURL = 'https://webrtcweb.com/RecordRTC/uploads/';
with the path to the file I created to hold these audio files (https://mywebsite.com/uploads)? Then set permissions for that folder to allow public write capabilities (this seems unsafe, is there a good method)?
This is the makeXMLHttpRequest function:
function makeXMLHttpRequest(url, data, callback) {
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
callback('upload-ended');
}
};
request.upload.onloadstart = function() {
callback('Upload started...');
};
request.upload.onprogress = function(event) {
callback('Upload Progress ' + Math.round(event.loaded / event.total * 100) + "%");
};
request.upload.onload = function() {
callback('progress-about-to-end');
};
request.upload.onload = function() {
callback('progress-ended');
};
request.upload.onerror = function(error) {
callback('Failed to upload to server');
console.error('XMLHttpRequest failed', error);
};
request.upload.onabort = function(error) {
callback('Upload aborted.');
console.error('XMLHttpRequest aborted', error);
};
request.open('POST', url);
request.send(data);
}
Please make sure that your PHP server is running top over SSL (HTTPs)
Create a directory and name it uploadFiles
Create a sub-directory and name it uploads
Structure of the directories:
https://server.com/uploadFiles -> to upload files
https://server.com/uploadFiles/uploads -> to store files
index.php
Now create or upload following index.php file on this path: https://server.com/uploadFiles
<?php
// File Name: "index.php"
// via https://github.com/muaz-khan/RecordRTC/tree/master/RecordRTC-to-PHP
foreach(array('video', 'audio') as $type) {
if (isset($_FILES["${type}-blob"])) {
echo 'uploads/';
$fileName = $_POST["${type}-filename"];
$uploadDirectory = 'uploads/'.$fileName;
if (!move_uploaded_file($_FILES["${type}-blob"]["tmp_name"], $uploadDirectory)) {
echo(" problem moving uploaded file");
}
echo($fileName);
}
}
?>
Why sub-directory?
Nested directory uploads will be used to store your uploaded files. You will get URLs similar to this:
https://server.com/uploadFiles/uploads/filename.webm
Longer file upload issues:
https://github.com/muaz-khan/RecordRTC/wiki/PHP-Upload-Issues
upload_max_filesize MUST be 500MB or greater.
max_execution_time MUST be at least 10800 (or greater).
It is recommended to modify php.ini otherwise create .htaccess.
How to link my own server?
Simply replace https://webrtcweb.com/RecordRTC/ with your own URL i.e. https://server.com/uploadFiles/.

View a PDF in React Native

Can anyone please provide sample code for displaying a PDF in React Native? iOS and Android.
This is what I've tried:
render: function() {
return <WebView
source={require('./my.pdf')}
/>
}
^ This results in a Red Screen of Death with the "Unable to resolve module" error.
render: function() {
return <WebView
source={{uri: 'my.pdf'}}
/>
}
^ This gives an "Error Loading Page" message in the WebView. "The requested URL was not found on this server"
I know iOS is capable of showing a PDF in a UIWebView. I assume Android can do the same. There must be something in how the source is specified that I'm missing.
Okay, for future generations, here's how I solved this problem:
Updated September 13, 2017:
There is a new NPM module that makes this entire process much easier. I would suggest using it going forward instead of my original answer below:
react-native-pdf
Once installed, rendering the PDF is as easy as this:
export default class YourClass extends Component {
constructor(props) {
super(props);
this.pdf = null;
}
render() {
let yourPDFURI = {uri:'bundle-assets://pdf/YourPDF.pdf', cache: true};
return <View style={{flex: 1}}>
<Pdf ref={(pdf)=>{this.pdf = pdf;}}
source={yourPDFURI}
style={{flex: 1}}
onError={(error)=>{console.log(error);}} />
</View>
}
}
Just put your actual pdf in the android/app/src/main/assets/pdf folder of your project.
Original Answer:
iOS
render: function() {
return <WebView source={{uri: 'My.pdf'}}/>
}
The trick is that you need to include My.pdf into your project in Xcode and make sure it's added to your build target.
Just copying it into your React Native project folder wasn't enough. It had to be part of the Xcode project itself.
Android
It appears that Android did not provide a native PDF viewer until 5.0 (Lollipop). To get around this, I've had to make use of three key techniques:
Pull the PDF out of my APK bundle and store it in the files folder for my app. This SO answer was very helpful in accomplishing this:
Android: How to copy files from 'assets' folder to sdcard?
I tweaked the code a bit so that the file wasn't going to an sdcard but to my app's files folder. Here's what I added to my MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AssetManager assetManager = getAssets();
String[] files = null;
try {
files = assetManager.list("pdf");
} catch (IOException e) {
Log.e("tag", "Failed to get asset file list.", e);
}
if (files != null) for (String filename : files) {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open("pdf/" + filename);
File outFile = new File(getFilesDir(), filename);
out = new FileOutputStream(outFile);
copyFile(in, out);
Log.e("tag", "Copy was a success: " + outFile.getPath());
} catch(IOException e) {
Log.e("tag", "Failed to copy asset file: " + "pdf/" + filename, e);
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// NOOP
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
// NOOP
}
}
}
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
}
I also made sure my PDF is in the assets/pdf folder under android/app/src/main
I then utilized the react-native-fs package to get the absolute URL to my PDF, which is now in the files folder:
var RNFS = require('react-native-fs');
var absolutePath = RNFS.DocumentDirectoryPath + '/My.pdf';
With all of this in place, I used react-native-pdf-view to actually load and display the PDF:
import PDFView from 'react-native-pdf-view';
render: function() {
var absolutePath = RNFS.DocumentDirectoryPath + '/My.pdf';
return <PDFView
ref={(pdf)=>{this.pdfView = pdf;}}
src={absolutePath}
style={ActharStyles.fullCover} />
}
Good luck!
A simple solution for this problem is to set <WebView> source/uri to this:
https://drive.google.com/viewerng/viewer?embedded=true&url={your pdf url}’
Just add style={{flex:1}} in the opening View Tag of your return and you should be fine.
The Amazon S3 Presigned URL contains query string contains "?" and "&" which confuses the outer URL.
So you have to Encode the S3 Presigned URL before passing it to the Google Doc Viewer.
Like this:
var encodedUrl = encodeURIComponent(presigned_url);
var iFrameUrl = 'https://docs.google.com/gview?url=' + encodedUrl;
In case of pdf url this will do
openLink(url) {
return Linking.canOpenURL(url)
.then(supported => {
if (!supported) {
console.log("Can't handle url: " + url);
this.showFlashMessage('Not supported in your device');
} else {
return Linking.openURL(url);
}
})
.catch(err => console.error('An error occurred', err));
}

Apache Cordova File API via Windows Phone

I have tried to use Apache Cordova File Plugin documentation
Here is my code. It just basically goes through all folders into file system.
function log(text) {
var element = document.createElement('div');
element.innerHTML = text;
document.getElementById("log").appendChild(element);
}
function onSuccess(fileSystem) {
function printEntries(entries) {
log("Enter printEntries function");
var i;
log("Number of entries" + entries.length);
for (i = 0; i < entries.length; i++) {
log("Interation number " + i);
if (entries[i].isFile) {
log(entries[i].name);
} else {
log("Moving into subdirectory name: " + entries[i].name);
entries[i].createReader().readEntries(printEntries, fail);
}
}
}
function fail(error) {
log("Failed to list directory contents: " + error.code);
}
// Get a directory reader
var directoryReader = fileSystem.root.createReader();
// Get a list of all the entries in the directory
directoryReader.readEntries(printEntries, fail);
}
// request the persistent file system
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onSuccess, null);
When I deploy my application to the my Lumia I have only this directories:
/
-Shared
---Media
---ShellContent
---Transfers
-debugOutput.txt
-DeviceID.txt
It seams that I have no access to files, that stored on my phone (images, videos).
So, my question is: Is it possible to get files from phone file system and sd card?

Access sd card in android for uploading a file to my php server using phonegap

I want to go to select a file from sdcard and upload it to server. is it possible to access the sdcard in android via phonegap as how we are picking a image from gallery and uploading. I went through samples but all are specifying the file name also like eg: mnt/sdcard/read.txt. But i want to goto only sdcard so that user can select his own file is it possible to do.
U can easily do that its very easy
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFileSystemSuccessUpload, fail);
function onFileSystemSuccessUpload(fileSystem) {
// get directory entry through root and access all the folders
var directoryReader = fileSystem.root.createReader();
// Get a list of all the entries in the directory
directoryReader.readEntries(successReader,fail);
}
function successReader(entries) {
var i;
for (i=0; i<entries.length; i++) {
//alert(entries[i].name);
if(entries[i].isDirectory==true)
{
var directoryReaderIn = entries[i].createReader();
directoryReaderIn.readEntries(successReader,fail);
}
if(entries[i].isFile==true)
{
entries[i].file(uploadFile, fail);
}
}
};
function uploadFile(file) {
var target=""; //the url to upload on server
var ft = new FileTransfer(),path = "file://"+ file.fullPath,name = file.name;
ft.upload(path, target, win, fail, { fileName: name });
// var ft = new FileTransfer();
//ft.upload(file.fullPath, target, win, fail, options);
function win(r) {
alert("Code = " + r.responseCode);
alert("Response = " + r.response);
alert("Sent = " + r.bytesSent);
}
function fail(error) {
alert("An error has occurred: Code = " + error.code);
}
}