I have tried this code but my app is crashing without showing any error , i couldnt figure out what is the error
const {config,fs} = RNFetchBlob;
const { params } = this.props.navigation.state;
let PictureDir = fs.dirs.PictureDir // this is the pictures directory. You can check the available directories in the wiki.
let options = {
fileCache: true,
addAndroidDownloads : {
useDownloadManager : false, // setting it to true will use the device's native download manager and will be shown in the notification bar.
notification : false,
path: PictureDir + "/me_image", // this is the path where your downloaded file will live in
}
}
config(options).fetch('GET',url).then((res) => {
alert('Done');
})
saveToCameraRoll = () => {
const{selectedImage, downlaodUrl} = this.state
let url = downlaodUrl[0].url;
ToastAndroid.show("Image is Saving...", ToastAndroid.SHORT)
if (Platform.OS === 'android'){
RNFetchBlob
.config({
fileCache : true,
appendExt : 'jpg'
})
.fetch('GET', url)
.then((res) => {
console.log()
CameraRoll.saveToCameraRoll(res.path())
.then((res) => {
console.log("save", res)
ToastAndroid.show("Image saved Successfully.", ToastAndroid.SHORT)
}).catch((error) => {
ToastAndroid.show("Ops! Operation Failed", ToastAndroid.SHORT)
})
})
} else {
CameraRoll.saveToCameraRoll(url)
.then(alert('Success', 'Photo added to camera roll!'))
ToastAndroid.show("Image saved Successfully.", ToastAndroid.SHORT)
}
}
Related
I suffer from uploading image to getstream service. And it doesn't upload image.
Here is my code. I get the following error.
Here is my code.
const filter = { type: 'messaging', members: { $in: [userInfo.id] } };
const sort = [{ last_message_at: -1 }];
let channels;
await chatClient.queryChannels(filter, sort, {
watch: false,
state: true,
}).then((response) => {
channels = response;
})
const file = this.state.avatar;
let avatarURI;
channels[0].sendImage(file).then((response) => {
avatarURI = response.file;
console.log(avatarURI);
})
i'm trying to save a profile picture and i save it with asyncStorage. store part working perfectly but if i close app and reopen it doesn`t show image.
i logging image uri and there is uri but cant solve the problem.
here is my code
this is image pick part
const ImagePick = async () => {
const options = {
title: 'Seçim yapınız.',
cancelButtonTitle: 'İptal',
takePhotoButtonTitle: 'Bir fotoğraf çek',
chooseFromLibraryButtonTitle: 'Galeriden seç',
chooseWhichLibraryTitle: 'Galeriden seç',
mediaType: 'photo',
storageOptions: {skipBackup: true, path: 'images'},
};
let isCameraPermitted = await requestCameraPermission();
let isStoragePermitted = await requestExternalWritePermission();
if (isCameraPermitted && isStoragePermitted) {
ImagePicker.showImagePicker(options, async response => {
//console.log('response', response);
if (response.didCancel) {
console.log('Kullanıcı fotoğraf seçimini iptal etti');
} else if (response.customButton) {
console.log('Özel butona tıklandı.');
} else if (response.error) {
console.log('error', 'Bir hata oluştu.');
} else {
console.log(response.fileName);
let uri = response.uri;
let path = response.uri;
if (Platform.OS === 'ios') {
path = '~' + path.substring(path.indexOf('/Documents'));
}
if (!response.fileName) {
response.fileName = path.split('/').pop();
}
let name = response.fileName;
let type = `image/${name.split('.').slice(-1)[0]}`;
console.log('uri', uri);
console.log('name', name);
console.log('type', type);
setImageUri(response.uri);
try {
await AsyncStorage.setItem('profilePicture', response.uri);
console.log('async storage kayıt başarılı');
} catch (error) {
console.log(error);
}
}
});
}
};
i get image like this
useEffect(() => {
getProfilePicture();
}, []);
const getProfilePicture = async () => {
const profilePicture = await AsyncStorage.getItem('profilePicture');
console.log('profilePicture', profilePicture);
if (profilePicture !== null) {
setImageUri(profilePicture);
setIsLoading(false);
} else {
setImageUri(
'https://t3.ftcdn.net/jpg/03/46/83/96/360_F_346839683_6nAPzbhpSkIpb8pmAwufkC7c5eD7wYws.jpg',
);
setIsLoading(false);
}
};
emulator is the problem. in device it's working
composeEmail = async () => {
const file = await this.downloadCsv();
const res = await RNFetchBlob.fs.exists(file.path);
if (res) {
const data = await RNFetchBlob.fs.readFile(file.path, 'base64');
console.log("encoded data", data)
if (Platform.OS === "ios") {
const shareOptions = {
social: Share.Social.EMAIL,
subject: '',
filename: file.filename.split(".")[0],
saveToFiles: file.path,
url: file.path,
type: 'csv',
failOnCancel: true,
}
try {
const ShareResponse = await Share.shareSingle(shareOptions);
} catch (error) {
console.log('Error:', error)
}
}
In that when we click on share button pop up the share screen but dismissed immediately.for that we also use Share.open(ShareOptions) but same result found.
I am using React-Native two days back After React-Native version upgrading to 0-62.2, I encountered many problems.
Among them important one is image upload error getting [Error:Network error ]
Before upgrading the React-native my code is working fine
Below code is working fine for me for multiple image upload before upgrading to React-Native 0.62.2 but now i am getting [Error: Network error]
constructor() {
super();
this.state = {
uploadPercentage: 0,
}
}
// upload Files upload_Files = async () => {
upload_File() {
if (this.validate_Fields()) {
const { image, images, files, description, userId, size } = this.state;
console.log('AddPost Screen : upload_File:', 'userId:', userId, 'Files:', files, 'description:', description)
// this.setState({ error: '', loading: true });
if (this.state.type === 'image/jpeg') {
console.log('AddPost Screen : upload_ files :', files);
const formData = new FormData();
formData.append('user_id', userId);
formData.append('description', description);
// formData.append('files[]', files);
for (let i = 0; i < files.length; i++) {
formData.append('files[]', {
name: files[i].path.split('/').pop(),
type: files[i].mime,
uri: Platform.OS === 'android' ? files[i].path : files[i].path.replace('file://', ''),
});
}
// upload percentage progress bar ******************************************************
const options = {
onUploadProgress: (progressEvent) => {
const { loaded, total } = progressEvent;
let percent = Math.floor((loaded * 100) / total)
console.log(`${loaded}kb of ${total}kb | ${percent}%`);
if (percent < 100) {
this.setState({ uploadPercentage: percent })
}
}
}
axios.post(API_URL + '/fileuploadapi/uploadPost', formData, options, {
headers: { "Content-type": "multipart/form-data" }
}).then((response) => {
console.log(JSON.parse(JSON.stringify(response.status)));
// upload percentage progress
this.setState({ uploadPercentage: 100 }, () => {
setTimeout(() => {
this.setState({ uploadPercentage: 0 })
}, 1000);
})
this.cleanupImages();
Alert.alert('Upload Post Successfully');
}).catch((error) => {
console.log(error);
this.cleanupImages();
Alert.alert('image Upload Post Failed , Try again !');
});
}
}
}
// clear files data
cleanupImages() {
this.setState({
description: '',
image: null,
images: null,
// video: '',
files: '',
uploadPercentage: 0,
})
ImagePicker.clean().then(() => {
console.log('removed tmp images from tmp directory');
}).catch(error => {
alert(error);
});
}
If anyone know the solution please let me know ...
I just found the solution for the React-Native 62.2 upgrading error for image upload Error
[Error: network error]
Just remove the file "ReactNativeFlipper.java" from debug/java folder
File Location :
android/app/src/debug/java/com/appname/ReactNativeFlipper.java
I am new on react native. I am getting blob response and try to save as pdf in storage using rn-fetch-blob. Using my code file saved into file storage but unable to show downloading notification.
Here is my code:
var date = new Date();
var path = RNFetchBlob.fs.dirs.DownloadDir + '/Inspection_' +Math.floor(date.getTime() + date.getSeconds() / 2)+'.pdf';
RNFetchBlob
.config({
// addAndroidDownloads : {
// useDownloadManager : true,
// title : 'Inspections_'+inspectionId,
// description : 'File successfully downloaded',
// // path:path,
// // mime : 'application/pdf',
// // mediaScannable : true,
// notification : true,
// }
})
.fetch('POST', url+'customer/create-pdf?id='+inspectionId, {
Accesstoken: 'Bearer '+this.token
})
.then((res) => {
console.log(res);
let base64Str = res.data;
// let pdfLocation = RNFetchBlob.fs.dirs.DownloadDir + '/Inspection_' +this.state.inspectionId+'.pdf';
RNFetchBlob.fs.writeFile(path, base64Str, 'base64');
// RNFetchBlob.android.actionViewIntent(path, 'application/pdf')
})
.catch((errorMessage, statusCode) => {
console.log(errorMessage);
console.log(statusCode);
})
How to set config to show notification.
You can use promise and Alert which will be triggered on downloading like this
RNFS.downloadFile({
fromUrl: newUrl,
background: true,
toFile: `${RNFS.DocumentDirectoryPath}/${fileName}`,
}).promise.then(async res => {
this.setState({
progress: 100,
loading: false,
downloaded: true,
popupMessage: "File downloaded successfully."
});
}).catch(err => {
this.setState({
loading: false
})
});
on downloaded flag you can show the alert or custom popup