From fea0d663da56a0edff7a2d61757ce11957eab5ad Mon Sep 17 00:00:00 2001 From: josetano2 Date: Fri, 23 Aug 2024 08:54:41 +0700 Subject: [PATCH] feat: upload image --- src/config/cloudinary.js | 2 +- src/ss_frontend/src/components/TextInput.jsx | 66 ++++++++++++++++---- 2 files changed, 56 insertions(+), 12 deletions(-) diff --git a/src/config/cloudinary.js b/src/config/cloudinary.js index 341036e..9ad534d 100644 --- a/src/config/cloudinary.js +++ b/src/config/cloudinary.js @@ -2,7 +2,7 @@ import { Cloudinary } from "@cloudinary/url-gen"; export const cld = new Cloudinary({ cloud: { cloudName: "dau03r7yn" } }); -export async function uploadImage({ file, onLoading }) { +export async function uploadImage(file, onLoading) { onLoading(true); const formData = new FormData(); formData.append("file", file); diff --git a/src/ss_frontend/src/components/TextInput.jsx b/src/ss_frontend/src/components/TextInput.jsx index 1db2fe6..a3991d6 100644 --- a/src/ss_frontend/src/components/TextInput.jsx +++ b/src/ss_frontend/src/components/TextInput.jsx @@ -1,9 +1,13 @@ -import React, { useState } from "react"; +import React, { useRef, useState } from "react"; import { HiOutlinePaperAirplane } from "react-icons/hi2"; import { LuImagePlus } from "react-icons/lu"; +import { uploadImage } from "../../../config/cloudinary"; const TextInput = () => { const [inputText, setInputText] = useState(""); + const [images, setImages] = useState([]); + const [loading, setLoading] = useState(false); + const fileInputRef = useRef(null); const handleSend = async () => { if (inputText.trim() === "") { @@ -11,16 +15,19 @@ const TextInput = () => { return; } - console.log(inputText) - + console.log(inputText); + try { - const response = await fetch("https://web-production-d8ae.up.railway.app/analyze", { - method: "POST", - headers: { - "Content-Type": "application/json", - }, - body: JSON.stringify({ comment: inputText }), - }); + const response = await fetch( + "https://web-production-d8ae.up.railway.app/analyze", + { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify({ comment: inputText }), + } + ); const data = await response.json(); if (response.ok) { @@ -33,6 +40,34 @@ const TextInput = () => { } }; + const handleImage = async (e) => { + if (e.target.files && e.target.files[0]) { + const file = e.target.files[0]; + const validatedFileTypes = ["image/jpeg", "image/png", "image/jpg"]; + + if (validatedFileTypes.includes(file.type)) { + try { + const url = await uploadImage(file, setLoading); + if (url) { + setImages((prevImages) => [...prevImages, url]); + } else { + throw new Error("Failed to upload image."); + } + } catch (error) { + console.log(error); + } + } else { + e.target.value = ""; + } + } + }; + + const handleImageClick = () => { + if (fileInputRef.current) { + fileInputRef.current.click(); + } + }; + return (
{ value={inputText} onChange={(e) => setInputText(e.target.value)} /> - + +