ImagePicker.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. /* eslint-disable no-underscore-dangle */
  2. import * as React from 'react';
  3. import { Platform, View } from 'react-native';
  4. import { Button, Icon, Image, Div } from 'react-native-magnus';
  5. import * as ImagePicker from 'expo-image-picker';
  6. import useModel from 'flooks';
  7. import request from '../Utils/RequestUtils';
  8. import Toast from '../flooks/Toast';
  9. const _pickImage = (aspect, loading) => {
  10. return ImagePicker.requestCameraRollPermissionsAsync()
  11. .then((res) => {
  12. if (!res.granted) {
  13. return Promise.reject('notAllod');
  14. } else {
  15. return ImagePicker.launchImageLibraryAsync({
  16. mediaTypes: ImagePicker.MediaTypeOptions.Images,
  17. allowsEditing: true,
  18. aspect: aspect || [1, 1],
  19. quality: 0.6,
  20. base64: true,
  21. });
  22. }
  23. })
  24. .then((res) => {
  25. if (!res.cancelled) {
  26. loading();
  27. if (Platform.OS === 'web') {
  28. return Promise.resolve(res.uri);
  29. }
  30. return Promise.resolve(res.base64);
  31. } else {
  32. return Promise.reject('cancel');
  33. }
  34. })
  35. .then((img) => {
  36. return request.post(`/upload/base64`, {
  37. data: { base64: img },
  38. requestType: 'form',
  39. });
  40. });
  41. };
  42. export default function ImagePickerCom(props) {
  43. const { aspect, img, setImg, cancelEvent, h, w } = props;
  44. const { loading, clearLoading } = useModel(Toast, []);
  45. return (
  46. <Div mr="sm" mb="sm">
  47. <Button
  48. bg="brand200"
  49. h={h || 67}
  50. w={w || 67}
  51. rounded="xs"
  52. onPress={() => {
  53. _pickImage(aspect || [1, 1], loading)
  54. .then((newImg) => {
  55. if (setImg) {
  56. setImg(newImg);
  57. }
  58. })
  59. .catch((e) => {
  60. console.log(e);
  61. })
  62. .finally(() => {
  63. clearLoading();
  64. });
  65. }}
  66. >
  67. {!img && <Icon name="plus" color="white" fontSize="4xl" />}
  68. {!!img && (
  69. <Image
  70. h={67}
  71. w={67}
  72. rounded="xs"
  73. source={{
  74. uri: img,
  75. }}
  76. />
  77. )}
  78. </Button>
  79. {cancelEvent && (
  80. <Button
  81. bg="red500"
  82. h={16}
  83. w={16}
  84. rounded="circle"
  85. position="absolute"
  86. right={-5}
  87. top={-5}
  88. onPress={cancelEvent}
  89. >
  90. <Icon name="minus" fontFamily="AntDesign" color="#fff" />
  91. </Button>
  92. )}
  93. </Div>
  94. );
  95. }