How to get video size in react native? - react-native

when uploading a video on, how to get its size.
I can set a limit to the duration but not the size.
I used this module
react-native-image-picker
this is the code used:
import ImagePicker from 'react-native-image-picker';
ImagePicker.showImagePicker(options, response => {
this.setState({ loading: false });
if (response.didCancel) {
console.log('User cancelled video picker');
} else if (response.error) {
console.log('ImagePicker Error: ', response.error);
} else {
let path = '';
if (Platform.OS === 'android') {
path = response.path;
} else {
path = response.uri;
}
const videoExtentionPos = path.lastIndexOf('.');
const videoExtention = path.substring(videoExtentionPos + 1);
this.setState({
fields: {
...fields,
posts_video: {
uri: response.uri,
type: `video/${videoExtention}`,
name: `video.${videoExtention}`
}
}
});
}
});

There is not direct way to get it done. You will need to check the file size and show alert if it is not what you expect.
You can get the file size with rn-fetch-blob package.
You can use react-native-fs as well.

Related

React-Native-Document-Picker, how to access file photo in ios w/ that?

im using react-native-document-picker but have problem on IOS. i cant open photo files. is there anyone ever face this issue ? and how to resolve this. please advise. below here is my code :
handleSuffixIcon={async () => {
try {
const pickerResult = await DocumentPicker.pickSingle({
presentationStyle: 'fullScreen',
copyTo: 'documentDirectory',
type:
Platform.OS === 'ios'
? ['public.jpeg', 'public.png', 'com.adobe.pdf']
: ['image/png', 'image/jpeg', 'application/pdf'],
});
if (pickerResult?.size <= 5000000) {
setSizeMsg('');
setUri(pickerResult?.fileCopyUri);
setDocument(pickerResult?.name);
setSize(pickerResult?.size);
setType(pickerResult?.type);
} else {
setUri('');
setDocument('');
setType('');
setSizeMsg({ error: trans(locale, lang, 'sizeToLarge') });
}
} catch (e) {
// eslint-disable-next-line no-console
console.log('error : ', e);
}
}}
my goals is to add more option like photo files. because in my project i have to send an image which is PNG/JPEG but also a document. and because i cant access my photo files. it really messy :(

how to implement an image and pdf picker in one single upload button in expo?

I am building a mobile app by using EXPO.Now i am stucked in a img & pdf picker,i can't pick image and pdf in one single function or button. can anyone know any packages that enable pdf & image picker in one function.....
You can use expo document picker to pick multiple file types and images as following:
import * as DocumentPicker from 'expo-document-picker';
const picker = await DocumentPicker.getDocumentAsync({
type: "*/*",
multiple: true,
copyToCacheDirectory: true
});
Check the official expo docs DocumentPicker
If you wanna allow your user to select pdf then you can do this
async function openDocumentPicker() {
try {
const res = await DocumentPicker.getDocumentAsync({
type: "*/*",
copyToCacheDirectory: true,
multiple: false,
});
console.log(res)
var lastThree = res.name.substr(res.name.length - 3);
if(lastThree == 'pdf')
{
if(res.type == 'success')
{
//Do Something here
}
}
else
{
alert('Please select PDF File')
}
} catch (error) {
alert(error);
}
}

DocumentPicker in React-Native not working properly for Android devices

I have implemented a document picker in my react native application and it is working fine for iOS. However in Android, I am having a weird issue
When I open the document picker and the navigation takes to the file explorer (Downloads section) in Android phone, though I am able to select the pdf file but, when it comes to the application back, it stuck to the page and the file is not there. I have attached the screenshot Same behaviour when the file explorer takes to the recent files. Only when from the recent files, I select the google drive and try to select the pdf from there, it works as expected and I can see the file in my application and the app do not stuck.
Here is what I have written for the pdf document picker
selectPDF = async ()=>{
var imageList = [...this.state.files];
try {
const results = await DocumentPicker.pickMultiple({
type: [DocumentPicker.types.pdf],
});
for (const res of results) {
console.log(
res.uri,
res.type, // mime type
res.name,
res.size
);
const fileName = res.uri.replace("file://","");
let data1 = ''
RnFetchBlob.fs.readStream(
fileName,
'base64',
4095
)
.then((ifstream)=>{
//let data1 = ''
ifstream.open()
ifstream.onData((data)=>{
data1 += data;
})
ifstream.onEnd(() => {
let base64 = data1
imageList.push({
imageName:res.name,
image:base64,
mime:res.type,
size:res.size
})
this.setState({
...this.state,
openCamera:false,
lastFileName:imageList[imageList.length - 1].imageName,
files:imageList
})
})
})
}
} catch (err) {
if (DocumentPicker.isCancel(err)) {
this.closeModal();
} else {
throw err;
}
}
}
Can anyone throw some light as to what I may be missing. Is some configuration needs to be set on device level or any other thing.
you can use something like this,
const [file, setFile] = useState(null);
const selectFile = async () => {
try {
const results = await DocumentPicker.pickMultiple({
type: [DocumentPicker.types.allFiles],
});
setFile(results);
} catch (err) {
if (DocumentPicker.isCancel(err)) {
alert('Canceled');
} else {
alert('Unknown Error: ' + JSON.stringify(err));
throw err;
}
}
};
now you can call file in your function
and to use it you can do like this
<TouchableOpacity
activeOpacity={0.5}
onPress={selectFile}>
<Text>Select File</Text>
</TouchableOpacity>

React Native Linking Promise resolved reject not getting called

I am using react native linking component for opening call application.call suggestion dialog get opened but when I click on cancel it does not return me any promise
static makePhoneCall = (mobileNumber) =>
{
let phoneNumber = '';
if (Platform.OS === 'android') {
let userMobile = `tel:${mobileNumber}`
phoneNumber = userMobile;
}
else {
let userMobile = `tel://${mobileNumber}`
phoneNumber = userMobile;
}
Linking.openURL(phoneNumber).then(() => {
alert('success')
}).catch(() => {
alert('failure')
});
return 'default`
}
classname.makePhoneCall(this.state.item.mobileNumber)
I want to know how to handle openUrl Promise with some example, I have share code of what I have done. I am using react native version 0.59.9
You should check to see if theres an app available to handle the url first.
Linking.canOpenURL(phoneNumber)
.then((supported) => {
if (!supported) {
console.log("Can't handle url: " + url);
} else {
return Linking.openURL(url);
}
})
.catch((err) => console.error('An error occurred', err));

React-native-image-picker: How to access gallery images directly in grid fashion

I am using react-native-image-picker and I would like to access gallery images directly from the device. However, when I launch ImageLibrary using the following method, I would see further 2 options saying "Pictures", "Download".
Instead I would like to see all the library images in grid fashion like below.
ImagePicker.launchImageLibrary(options, (response) => {
if (response.didCancel) {
console.log('User cancelled photo picker');
}
else if (response.error) {
console.log('ImagePicker Error: ', response.error);
}
else if (response.customButton) {
console.log('User tapped custom button: ', response.customButton);
}
else {
this.props.navigation.navigate('AddImage', {uri: response.uri, addImage: this.addImage.bind(this)});
}
});
I have a little bit idea but Not much that you have asked.
It just directly launch Camera and Image library only. maybe helpful to you.
// Launch Camera:
ImagePicker.launchCamera(options, (response) => {
// Same code as in above section!
});
// Open Image Library:
ImagePicker.launchImageLibrary(options, (response) => {
// Same code as in above section!
});
For more, Click here