From 5ff2c7971f38cdfc77612900edba4d5ba3ef76ff Mon Sep 17 00:00:00 2001 From: Adolfo Reyna Date: Tue, 22 Nov 2022 08:44:17 -0500 Subject: [PATCH] (Partial) Photo picker for new posts --- components/NewPost.js | 89 ++++++++++++++++++++++++++++---- package-lock.json | 117 ++++++++++++++++++++++++++++++++++++------ package.json | 3 +- 3 files changed, 181 insertions(+), 28 deletions(-) diff --git a/components/NewPost.js b/components/NewPost.js index e341acb..a84e761 100644 --- a/components/NewPost.js +++ b/components/NewPost.js @@ -1,13 +1,67 @@ import React, { useState } from 'react'; -import { View, StyleSheet } from 'react-native'; +import { View, StyleSheet, Image } from 'react-native'; import { TextInput, Button } from 'react-native-paper'; import API from './../API.js'; import { useNavigation } from '@react-navigation/native'; +import * as ImagePicker from 'expo-image-picker'; -let NewPost = ({profileid, newPostCB}) => { +let NewPost = ({ profileid, newPostCB }) => { let [postContent, setPostContent] = useState(''); const navigation = useNavigation(); + const [photo, setPhoto] = React.useState(null); + + + const pickImage = async () => { + // No permissions request is necessary for launching the image library + let result = await ImagePicker.launchImageLibraryAsync({ + mediaTypes: ImagePicker.MediaTypeOptions.Images, + //allowsEditing: true, + //aspect: [4, 3], + //quality: 1, + allowsMultipleSelection: true, + }); + if (!result.cancelled) { + setPhoto(result); + await handleUploadPhoto(result); + } + }; + + const handleUploadPhoto = async (photo) => { + if (!photo) return; + const uri = + Platform.OS === "android" + ? photo.uri + : photo.uri.replace("file://", ""); + const filename = photo.uri.split("/").pop(); + const match = /\.(\w+)$/.exec(filename); + const ext = match?.[1]; + const type = match ? `image/${match[1]}` : `image`; + const formData = new FormData(); + formData.append("banner", { + uri, + name: `image.${ext}`, + type, + }); + try { + fetch("https://social.emmint.com/upload.php", { + method: "POST", + body: formData, + headers: { "Content-Type": "multipart/form-data" } + }) + .then((res) => res.json()) + .then((data) => { + console.log(data); + return data.fileName; + }) + .catch((err) => console.error(err)); + } catch (err) { + console.log(err); + alert("Something went wrong"); + } + }; + + return ( @@ -20,16 +74,29 @@ let NewPost = ({profileid, newPostCB}) => { /> { postContent ? ( - - - + - + API.newPost(postContent).then((newPost) => { + setPostContent(''); + if (newPostCB) newPostCB(newPost); + }); + }}>Post + + {photo && ( + + + +