@@ -2,11 +2,18 @@ import { useState } from "react";
2
2
import { styled } from "@mui/material/styles" ;
3
3
import { Button , ImageList , ImageListItem } from "@mui/material" ;
4
4
import FileUploadIcon from "@mui/icons-material/FileUpload" ;
5
- import "react-toastify/dist/ReactToastify.css" ;
5
+ import { toast } from "react-toastify" ;
6
+ import axios from "axios" ;
6
7
8
+ import { questionClient } from "../../utils/api" ;
7
9
import QuestionImage from "../QuestionImage" ;
8
10
import QuestionImageDialog from "../QuestionImageDialog" ;
9
11
12
+ interface QuestionImageContainerProps {
13
+ uploadedImagesUrl : string [ ] ;
14
+ setUploadedImagesUrl : React . Dispatch < React . SetStateAction < string [ ] > > ;
15
+ }
16
+
10
17
const FileUploadInput = styled ( "input" ) ( {
11
18
height : 1 ,
12
19
overflow : "hidden" ,
@@ -16,14 +23,9 @@ const FileUploadInput = styled("input")({
16
23
width : 1 ,
17
24
} ) ;
18
25
19
- interface QuestionImageContainerProps {
20
- handleImageUpload : ( event : React . ChangeEvent < HTMLInputElement > ) => void ;
21
- uploadedImagesUrl : string [ ] ;
22
- }
23
-
24
26
const QuestionImageContainer : React . FC < QuestionImageContainerProps > = ( {
25
- handleImageUpload,
26
27
uploadedImagesUrl,
28
+ setUploadedImagesUrl,
27
29
} ) => {
28
30
const [ open , setOpen ] = useState < boolean > ( false ) ;
29
31
const [ selectedValue , setSelectedValue ] = useState < string > ( "" ) ;
@@ -37,6 +39,49 @@ const QuestionImageContainer: React.FC<QuestionImageContainerProps> = ({
37
39
setOpen ( false ) ;
38
40
} ;
39
41
42
+ const handleImageUpload = async ( event : React . ChangeEvent < HTMLInputElement > ) => {
43
+ if ( ! event . target . files ) {
44
+ return ;
45
+ }
46
+
47
+ const formData = new FormData ( ) ;
48
+ for ( const file of event . target . files ) {
49
+ if ( ! file . type . startsWith ( "image/" ) ) {
50
+ toast . error ( `${ file . name } is not an image` ) ;
51
+ continue ;
52
+ }
53
+
54
+ if ( file . size > 5 * 1024 * 1024 ) {
55
+ toast . error ( `${ file . name } is more than 5MB` ) ;
56
+ continue ;
57
+ }
58
+ formData . append ( "images[]" , file ) ;
59
+ }
60
+
61
+ try {
62
+ const response = await questionClient . post ( "/images" , formData , {
63
+ headers : {
64
+ "Content-Type" : "multipart/form-data" ,
65
+ } ,
66
+ withCredentials : false ,
67
+ } ) ;
68
+
69
+ const data = response . data ;
70
+ for ( const imageUrl of data . imageUrls ) {
71
+ setUploadedImagesUrl ( ( prev ) => [ ...prev , imageUrl ] ) ;
72
+ }
73
+
74
+ toast . success ( "File uploaded successfully" ) ;
75
+ } catch ( error ) {
76
+ if ( axios . isAxiosError ( error ) ) {
77
+ toast . error ( error . response ?. data . message || "Error uploading file" ) ;
78
+ } else {
79
+ console . error ( error ) ;
80
+ toast . error ( "Error uploading file" ) ;
81
+ }
82
+ }
83
+ } ;
84
+
40
85
if ( uploadedImagesUrl . length === 0 ) {
41
86
return (
42
87
< Button
0 commit comments