i'm trying to read the content of the doc file which is picked by a user to find a specific word in that document.
const res = await DocumentPicker.pick({
type: [DocumentPicker.types.docx, DocumentPicker.types.doc],
});
i just want to read the content and find a specific word in that string from doc or docx file.
i have tried with react-native-fs to read at a specific address but it didn’t work in that way.
import RNFS from "react-native-fs";
RNFS.readFile(res.uri).then((data) => {
console.log(data);
})
Related
I'm trying to Download txt file from a text but that function is not working fine.
Txt Function
import RNFS from 'react-native-fs';
const txtDownload = () => {
let path = `${RNFS.DocumentDirectoryPath}/${filename}.txt`;
RNFS.writeFile(path, `Here is text`, 'utf8').then((res) => {
Toast('File saved successfully');
}
).catch((err) => {
Toast(err);
});
}
It returns File saved successfully but I can't find file
Log the path and check the location where it's trying to store. For me, it shows the location as below when I try to store in ${RNFS.DocumentDirectoryPath}/help.txt
/data/user/0/com.sample/files/help.txt
I suspect you were checking in the Documents folder. I don't know if you can write to the Documents folder. But it works for the Download folder using RNFS.DownloadDirectoryPath.
I am using React Native Share library, a good one,
I just need little help,
It is sharing multiple images with same caption,
i just want to share multiple images with separate message (caption) to each image,
suppose, if there is 5 images, then caption to 5 images is different not same.
In current situation, it share 5 images with same message (caption)
Here is my code
var imgs=["base64IMAGE1...///","base64IMAGE2..///","base64IMAGE3..///"];
let shareImage = {
title:"title",
message:"this is message need to send separate to each image",
urls:abcc,
subject: "Image"
};
Share.open(shareImage).catch(err => console.log(err));
I have attached current situation screenshots..
image 1 on whatsapp
image 2 on whatsapp
all sent with same caption, i just to send multiple images with separate messages
ThankYou.
I've created working example to share multiple or single images using react-native-share
CheckOut ExpoSnack Here
added comments before every method what it'll do and what needs to be replaced.
// multiple images share example
const shareMultipleImages = async () => {
const shareOptions = {
title: 'Share multiple files example',
// here replace base64 data with your local filepath
// base64 with mimeType or path to local file
urls: [base64ImagesData.image1, base64ImagesData.image2],
failOnCancel: false,
};
// If you want, you can use a try catch, to parse
// the share response. If the user cancels, etc.
try {
const ShareResponse = await Share.open(shareOptions);
setResult(JSON.stringify(ShareResponse, null, 2));
} catch (error) {
console.log('Error =>', error);
setResult('error: '.concat(getErrorString(error)));
}
};
you can add local file path in shareMultipleImage method like this
urls: Array of base64 string you want to share. base64 with mimeType or path to local file (Array[string])
React Native Share Docs
const shareOptions = {
title: 'Share multiple files example',
urls: ["file..///","file..///","file..///"],
failOnCancel: false,
};
I have some problem about my react native app. I would just like to ask if are there any ways that RNFetchBlob will accept a dataURI from documentPicker instead of a web URL? I just need to convert the selected file from document picker to base64. Could anyone help me?
RNFetchBlob.config({ fileCache: true })
.fetch("GET", 'http://www.africau.edu/images/default/sample.pdf') // Replace the web URL to dataURI from documentPicker
// the image is now dowloaded to device's storage
.then(resp => {
// the image path you can use it directly with Image component
// return resp.readFile("base64");
return resp.readFile("base64");
}).then(base64Data => {
console.log('base64Data', base64Data);
});
If you are not particularly looking for base64 encoded but want to obtain the actual blob you can use fetch without going through base64 bridge
const fetchResponse = await fetch(at[i].uri);
const blob = await fetchResponse.blob();
I am uploading an image file using nodeJS and express and currently, image is saved with a random file name with no specific file type. I want to save the file name with an extension so that I could display it as well, because currently in DB file name is saved as the original file but in the upload folder, it assigns a random name (string) and when I fetch that back I have no clue how to display it as it does not have any file type/extension,i.e. .png/JPEG.
//Schema
const AddProductSchema = new Schema({
productCode: String,
productTitle: String,
productImage: String
//defined express, mongoose, multer and upload const for the directory
const upload = multer({
dest: __dirname + '/uploads/images'
});
//post method
app.post("/addProductToDB", upload.single("productImage"), function(req, res) {
// to get the detail filled on add product form
const addproduct = new AddProduct({
productCode: req.body.productCode,
productTitle: req.body.productTitle,
productImage: req.file.originalname
});
addproduct.save();
res.redirect("/products");
});
You should save productImage with buffer type if you want to display image productImage: Buffer
There's a package called sharp which can help you customize image file before save to database called sharp https://www.npmjs.com/package/sharp
If you want to have png file type before saving, you can use the following code
const buffer = await sharp(req.file.buffer)
.png()
.toBuffer();
Then you just need to save buffer to your productImage: buffer
A multilingual react-native app. Each language bundle is ~50MB. It doesn't make sense to include all of them in a bundle. So, what do I do about it?
I assume the right way to go here is to download the respective language files upon language selection.
What do I do with it next? Do I suppose to store it using AsyncStorage or what?
Briefly explaining, you will:
Store JSON as ZIP in Google Storage (save memory/bandwidth/time)
Unzip file to JSON (in RN)
Store JSON in AsyncStorage (in RN)
Retrieve from AsyncStorage (in RN)
[Dependencies Summary] You can do this, using these deps:
react-native
react-native-async-storage
rn-fetch-blob
react-native-zip-archive
Tip: Always store big language json in zip format (this can save up to 90% of size).
I made a quick test here: one 3.52MB json file, turned out a 26KB zipped file!
Let's consider that yours stored zip file, can be accessed by using a public url, eg: https://storage.googleapis.com/bucket/folder/lang-file.zip.
Install and link all above RN deps, it's required to get this working.
Import the deps
import RNFetchBlob from 'rn-fetch-blob';
import { unzip } from 'react-native-zip-archive';
import AsyncStorage from '#react-native-community/async-storage';
Download the file using rn-fetch-blob. This can be done using:
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())
// Unzip will be called here!
unzipDownloadFile(res.path(), (jsonFilePath) => {
// Let's store this json.
storeJSONtoAsyncStorage(jsonFilePath);
// Done!
// Now you can read the AsyncStorage everytime you need (using function bellow).
});
});
[function] Unzip the downloaded file, using react-native-zip-archive:
function unzipDownloadFile(target, cb) {
const targetPath = target;
const sourcePath = `${target}.json`;
const charset = 'UTF-8';
unzip(sourcePath, targetPath, charset)
.then((path) => {
console.log(`unzip completed at ${path}`)
return cb(path);
})
.catch((error) => {
console.error(error)
});
}
[function] Store JSON in AsyncStorage:
function storeJSONtoAsyncStorage (path) {
RNFetchBlob.fs.readFile(path, 'utf-8')
.then((data) => {
AsyncStorage.setItem('myJSON', data);
});
}
Retrieve JSON data from AsyncStorage (everytime you want):
AsyncStorage.getItem('myJSON', (err, json) => {
if (err) {
console.log(err);
} else {
const myJSON = JSON.parse(json);
// ... do what you need with you json lang file here...
}
})
That's enough to get dynamic json lang files working in React Native.
I'm using this approach to give a similar feature to my i18n'ed project.
Yes you are right to make the translation file downloadable.
You can store the downloaded file in the document directory of your app.
After that you can use a package to load the translations. For instance
https://github.com/fnando/i18n-js.
I would also suggest taking a look at the i18n library which is a standard tool for internationalisation in JavaScript.
Consider taking a look at this documentations page where you can find an option of loading a translation bundle or setting up a backend provider and hooking into it.
Also, to answer the storage question, if you do not plan on setting up a backend: AsyncStorage would be an appropriate place to store your key - translation text pairs.