I am currently using image picker and image manipulator in my project for uploading and compressing the image. But I want to show user that he cannot upload image greater than any particular size(let’s say 5mb). How can I achieve this in react- native?
Advertisement
Answer
I’m actually doing this exact thing with ImagePicker in my app. Here’s how I do it:
JavaScript
x
18
18
1
const result = await ImagePicker.launchImageLibraryAsync({
2
mediaTypes: "Images",
3
allowsEditing: true,
4
base64: true,
5
quality: 1,
6
});
7
8
if (!result.cancelled) {
9
const fileSize = result.base64.length * (3 / 4) - 2;
10
if (fileSize > 6000000) {
11
setFileSizeError(true);
12
} else {
13
setFileSizeError(false);
14
const base64 = `data:image/png;base64,${result.base64}`;
15
await dispatch(myExampleAction(base64));
16
}
17
}
18
File size is calculated by the function -your base64 string length- * (3 / 4) - 2
. Where at the end - 2
depends on how many ==
your base64 is trailed by. For example just one =
would be - 1
instead.
Also fileSizeError
is set by setFileSizeError
. And will switch the boolean if it’s bigger than 6000000 bytes.