Skip to content

Commit

Permalink
feat: 이미지 크기 제한, 상품 수정 시 이전 이미지 가져오도록 수정
Browse files Browse the repository at this point in the history
  • Loading branch information
kjh9852 committed Oct 7, 2024
1 parent ef07e06 commit 339f59c
Showing 1 changed file with 30 additions and 11 deletions.
41 changes: 30 additions & 11 deletions src/ui/FormComponents/FileInput.tsx
Original file line number Diff line number Diff line change
@@ -1,42 +1,50 @@
import { MouseEvent, ChangeEvent, useState, useEffect, useRef } from "react";
import { FileInputProps } from "../@types/Input";
import { imageUpload } from "../../utils/http";
import ErrorComponent from "../../components/Error/ErrorComponent";
import styles from "./FileInput.module.css";

const MAX_FILE_SIZE = 5 * 1024 * 1024;

export default function FileInput({
id,
name,
previewImg,
changeValue,
value,
className,
...props
}: FileInputProps) {
const [preview, setPreview] = useState<string | null>(null);
const [preview, setPreview] = useState<string | null>(previewImg ?? null);
const [file, setFile] = useState<File | null>(null);
const [isError, setIsError] = useState<boolean>(false);
const [message, setMessage] = useState<string>("");
const fileInputRef = useRef(null);

const handleChange = async (e: ChangeEvent<HTMLInputElement>) => {
const imgValue = e.target.files?.[0] || null;
const imgValue = e.target.files?.[0];
if (imgValue) {
console.log(imgValue);
setFile(imgValue);
if (imgValue.size > MAX_FILE_SIZE) {
setIsError(true);
setMessage("업로드 파일 최대 크기는 5MB입니다.");
return;
}
try {
const response = await imageUpload(imgValue);
console.log(response);
setFile(imgValue);
changeValue(name, response.url);
} catch (error) {
console.log(error);
setIsError(true);
throw new Error("예기치 않은 오류가 발생했습니다.");
}
}

changeValue(name, imgValue);
};

const handleRemoveImage = (e: MouseEvent<HTMLElement>) => {
e.preventDefault();
fileInputRef.current.value = null;
setFile((prev) => (prev = null));
changeValue(name, null);
setPreview(null);
changeValue(name, "");
};

useEffect(() => {
Expand All @@ -49,8 +57,19 @@ export default function FileInput({
};
}, [file]);

const handleResetIsError = () => {
setIsError(false);
};

return (
<div className={styles.previewImgContainer}>
{isError && (
<ErrorComponent
isOpen={isError}
onResetError={handleResetIsError}
message={message}
/>
)}
<label htmlFor={id} className={styles.fileLabel}>
<span>이미지 등록</span>
</label>
Expand All @@ -60,7 +79,7 @@ export default function FileInput({
id={id}
{...props}
onChange={handleChange}
accept="image/png, image/jpeg"
accept="image/png, image/jpeg, image/gif"
/>
{preview && (
<div className={styles.previewImg}>
Expand Down

0 comments on commit 339f59c

Please sign in to comment.