-
const [isFile, setIsFile] = useState<File[] | null>(null); /* 사진 업로드 */ const fileInputRef = useRef<HTMLInputElement | null>(null); const navigate = useNavigate(); function saveFile(imageFile: File[]) { setIsFile(imageFile); // setUploadLocation(true); navigate("/upload"); } function handleAddPicBtn() { fileInputRef.current && fileInputRef.current.click(); } function handleFileInputChange(e: React.ChangeEvent<HTMLInputElement>) { if (e.target.files) { const fileList = Array.from(e.target.files); saveFile(fileList); } console.log(isFile); } /*적용할 때*/ <Container type="button" key={date} onClick={handleAddPicBtn}> <img src={blankImg} /> <FileInput type="file" ref={fileInputRef} multiple={false} onChange={handleFileInputChange} accept="image/gif,image/jpeg,image/png,image/jpg,image/webp,image/heic" /> </Container>
/*상위 컴포넌트*/ const [isImageUploaded, setImageUploaded] = useState(false); const handleImageUpload = () => { setImageUploaded(true); }; <ProfileUpload onImageUpload={handleImageUpload} /> /*ProfileUpload 이미지 업로드*/ const ProfileUpload = ({ onImageUpload }: { onImageUpload: () => void }) => { const inputRef = useRef<HTMLInputElement>(null); const [, setmodelImgUrl] = useState<File>(); const [, isVerified] = useState(true); const uploadImg = (event: React.ChangeEvent<HTMLInputElement>) => { const imgObj = event.target.files; readImg({ input: imgObj, setUrl: setmodelImgUrl, setVerified: isVerified }); onImageUpload(); }; /*적용할 때*/ <S.ProfileUploadBtn type="button" onClick={() => { inputRef.current?.click(); }}> <S.Profile src={beforeUpload} alt="profileImg" id="profileImg" /> <input id="uploadButton" name="uploadButton" ref={inputRef} type="file" accept="image/*" onChange={(e) => { uploadImg(e); }} /> <IcPencilcircle /> </S.ProfileUploadBtn> /*커스텀 훅*/ export interface readImgProps { input: FileList | null; setUrl: React.Dispatch<React.SetStateAction<File | undefined>>; setVerified: React.Dispatch<React.SetStateAction<boolean>>; } export const readImg = ({ input, setUrl, setVerified }: readImgProps) => { // 인풋 태그에 파일이 있는 경우 if (input && input[0]) { // FileReader 인스턴스 생성 const reader = new FileReader(); // reader가 이미지 읽도록 하기 reader.readAsDataURL(input[0]); setUrl(input[0]); setVerified(false); // 이미지가 로드가 된 경우 reader.onload = (e) => { const previewImg = document.getElementById('profileImg') as HTMLImageElement; if (typeof e.target!.result === 'string') { previewImg.src = e.target!.result; } }; } };
댓글