I want to play a video but i face the can't play this video file error
When I try it with this link, the video is properly downloaded and also played but with this link, it says the video file is corrupt.
const downloadFile = () => {
const uri = "instagram.com/p/CET9SzMpCYg/?utm_source=ig_web_copy_link"
let fileUri = FileSystem.documentDirectory +"video.mp4";
FileSystem.downloadAsync(uri,fileUri)
.then(({ uri }) => { saveFile(uri); })
.catch(error => { console.error(error); })
}
const saveFile = async fileUri => {
const { status } = await Permissions.askAsync(Permissions.CAMERA_ROLL);
if (status === "granted") {
const asset = await MediaLibrary.createAssetAsync(fileUri);
await MediaLibrary.createAlbumAsync("Download", asset, false);
alert('Saved to Downloads');
}
}
Related
I'm pretty new using React Native (Expo in this case) and Firebase database.
My problem is that when I upload an image in my app thanks to Image Picker, the link is a local link, so reading only with my device, and then deleted when I erase the cache
Here is my code :
useEffect(() => {
(async () => {
if (Platform.OS !== "web") {
const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync();
if (status !== "granted") {
alert("Sorry, we need camera roll permissions to make this work!");
}
}
})();
}, []);
const pickImage = async () => {
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.All,
allowsEditing: true,
quality: 1,
});
if (!result.cancelled) {
setImage(result.uri);
}
};
// My current image is locate to : "file:///data/user/0/host.exp.exponent/cache/
// ExperienceData/ImagePicker/2abe4097-05ed-4d23-5648-f279d5a6f995.jpg"
// And what I want is to locate my image to : "https://someting..."
So I want to convert this image uri link in a url link, to be shared and never erased.
Anyone has an idea about how to proceed ?
Thanks a lot !
Let's break down the problem as below :
1. Pick an image from the Media Library.
const pickImage = async () => {
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.All,
allowsEditing: true,
quality: 1,
});
if (!result.cancelled) {
setImage(result.uri);
}
};
2. Fetch Image BLOB Data
const blob = await new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.onload = function () {
resolve(xhr.response);
};
xhr.onerror = function (e) {
reject(new TypeError("Network request failed"));
};
xhr.responseType = "blob";
xhr.open("GET", [IMAGE_URI_HERE], true);
xhr.send(null);
});
3. Upload image BLOB to a remote server (Firebase Storage)
const metadata = { contentType: "image/jpg" };
const imgRef = firebase.storage().ref('folderName/fileName');
await imgRef.put(blob, metadata);
// We're done with the blob, close and release it
blob.close();
// Image permanent URL
const imgURL = await imgRef.getDownloadURL();
I'm having trouble saving a .DOC file using expo-file-system.
I'm getting the following feedback:
[Unhandled promise rejection: Error: Invalid argument "localUri". It
must be a string!]
This is my current code:
useEffect(() => {
const saveFile = async () => {
const { granted } = await Notifications
.requestPermissionsAsync()
.then((response) => response)
.catch((error) => error);
console.log(granted);
if (granted) {
data.map(async (index) => {
const date = new Date(index.synchronization)
const formattedDate = date.toISOString().split('T')[0];
const fileUri = `${FileSystem.documentDirectory}${formattedDate}.doc`;
console.log(fileUri)
await FileSystem.writeAsStringAsync(
fileUri,
"Hello World, i'am saving this file :)",
{
encoding: FileSystem.EncodingType.UTF8
});
const asset = await MediaLibrary.createAssetAsync(`${fileUri}`);
await MediaLibrary.createAssetAsync(asset);
console.log(asset);
});
}
}
saveFile();
}, [data]);
The error is probably occurring on this line:
const asset = await MediaLibrary.createAssetAsync(`${fileUri}`);
await MediaLibrary.createAssetAsync(asset);
Okay, I did!
It's a boring prank these promises
const { uri } = await MediaLibrary
.createAssetAsync(`${fileUri}`)
.then((response) => response)
.catch((error) => error);;
await MediaLibrary.createAssetAsync(uri);
Necessita do uso de then and catch
I have tried to research for the right answer for me on saving captured images or videos to custom folder on device but have not seen a suitable answers. I have been able to save to my DCIM, but I don't want to save them there, I want to create a custom folder to save my captured images or video from my app. I am new to react native and this is my learning process...
takePicture = async () => {
if (this.camera) {
if (Platform.OS === 'android') {
await this.checkAndroidPermission();
}
const options = { quality: 1 };
const data = await this.camera.takePictureAsync(options);
//save photo
CameraRoll.save(data.uri, 'photo').then(onfulfilled => {
ToastAndroid.show(`VidApp Photos: ${onfulfilled}`, ToastAndroid.SHORT);
}).catch(error => {
ToastAndroid.show(`${error.message}`, ToastAndroid.SHORT);
});
}
};
recordVideo = async () => {
if (this.camera) {
if (!this.state.recording)
this.startRecording();
else this.stopRecording();
}
}
startRecording = async () => {
this.setState({ recording: true });
this.countRecordTime = setInterval(() => this.setState({ seconds: this.state.seconds + 1 }), 1000);
const cameraConfig = { maxDuration: this.state.maxDuration };
const data = await this.camera.recordAsync(cameraConfig);
this.setState({ recording: false });
CameraRoll.save(data.uri, 'video').then(onfulfilled => {
ToastAndroid.show(`VidApp Videos: ${onfulfilled}`, ToastAndroid.SHORT)
}).catch(error => ToastAndroid.show(`${error.message}`, ToastAndroid.SHORT));
}
stopRecording = () => {
this.camera.stopRecording();
clearInterval(this.countRecordTime);
this.setState({ seconds: 0 });
You have to use the album parameter of CameraRoll.save
CameraRoll.save(data.uri, {type:'photo',album:'CustomFolder'});
from the docs
It allows to specify a particular album you want to store the asset to
when the param album is provided. On Android, if no album is provided,
DCIM directory is used, otherwise PICTURE or MOVIES directory is used
depending on the type provided.
I am trying to save captured images and video recording from phone camera to my device gallery, but I get permission denied and error message stating that CameraRoll.saveToCameraRoll(tag, type) is deprecated. Use the save function instead.
takePicture = async () => {
if (this.camera) {
const options = { quality: 1 };
const data = await this.camera.takePictureAsync(options);
//save photo
CameraRoll.saveToCameraRoll(data.uri, 'photo').then(onfulfilled => {
ToastAndroid.show(onfulfilled, ToastAndroid.SHORT);
}).catch(error => {
ToastAndroid.show(`${error.message}`, ToastAndroid.SHORT);
});
}
};
Assuming you are using the new version of CameraRoll the function saveToCameraRoll is being deprecated in favor of the save function. Only change that you have to do is to change saveToCameraRoll to save like below
takePicture = async () => {
if (this.camera) {
const options = { quality: 1 };
const data = await this.camera.takePictureAsync(options);
//save photo
CameraRoll.save(data.uri, 'photo').then(onfulfilled => {
ToastAndroid.show(onfulfilled, ToastAndroid.SHORT);
}).catch(error => {
ToastAndroid.show(`${error.message}`, ToastAndroid.SHORT);
});
}
};
I need way to upload image to firebase
i tried to use react-native-fetch-blob library
but I think there is something wrong with installing the library
No need to use react-native-fetch-blob. Here is how I do it on my project.
Install both react-native-firebase and react-native-image-picker. Follow the installation steps from their documentation guide.
Then implement 2 small functions to do image pick and upload to firebase. Here is the sample code.
// 1. Import required library
import firebase from 'react-native-firebase';
import ImagePicker from 'react-native-image-picker';
// 2. Create a function to pick the image
const pickImage = () => {
return new Promise((resolve, reject) => {
ImagePicker.showImagePicker(pickerOptions, response => {
if (response.didCancel) return;
if (response.error) {
const message = `An error was occurred: ${response.error}`;
reject(new Error(message));
return;
}
const { path: uri } = response;
resolve(uri);
});
});
};
// 3. Create a function to upload to firebase
const uploadImage = async (fileName, uri) {
return new Promise(
(resolve, reject) => {
firebase
.storage()
.ref(`uploads/${filename}`)
.putFile(uri)
.then(resolve)
.catch(reject);
}
);
}
Then simply firing both function as you need, here is the sample to pick and immediately upload it.
const pickImageAndUpload = async () => {
const uri = await pickImage();
const fileName = 'someImage.jpg';
const { state, downloadURL } = await uploadImage(fileName, uri);
}
async function uploadImageAsync(itemImage, passedParameter, ItemName, ItemDesc, ItemPrice, ItemWeight) {
const response = await fetch(itemImage);
const blob = await response.blob();
console.log("uri of the elements ius", blob)
var storageRef = firebase.storage().ref();
var file = blob
var metadata = {
contentType: 'image/jpeg',
};
const timeStamp = Date.now();
var uploadTask = storageRef.child('CategoryDescription' + "/" + `${passedParameter}` + "/" + `${ItemName}`).put(file, metadata);
//For image pick
pickImage = async () => {
const { CAMERA, CAMERA_ROLL } = Permissions;
const permissions = {
[CAMERA]: await Permissions.askAsync(CAMERA),
[CAMERA_ROLL]: await Permissions.askAsync(CAMERA_ROLL),
};
if (permissions[CAMERA].status === 'granted' && permissions[CAMERA_ROLL].status === 'granted') {
let result = await ImagePicker.launchImageLibraryAsync({
allowsEditing: false,
aspect:[4,3],
quality: 0.5,
});
// console.log(result);
if (!result.cancelled) {
this.setState({ itemImage: result.uri });
}
}