rhanziy

React - image file 업로드 및 preview 구현 본문

React

React - image file 업로드 및 preview 구현

rhanziy 2023. 2. 9. 17:49

firebase로 sso기능 만들고 firestore에 사진+트윗 올리는 기능 만드는 중.

image file 업로드와 preview 구현 코드. 사진 저장은 firestore에다 할 것이니 조금만 기다리세요.

 

 

file 업로드 처리, 미리보기 코드

     const [ attachment , setAttachment ] = useState();

 
 	const onFileChange = (e) => {
        const { files } = e.target;
        const theFile = files[0];
        const reader = new FileReader();
        reader.onloadend = (e) => {
            const { result } = e.currentTarget;
            setAttachment(result);
        }
        reader.readAsDataURL(theFile);
    }

    const onClearPhoto = () => setAttachment(null);

파일을 찾고 이미지 업로드를 하면, 이벤트리스너 files 속성 값에 이미지 속성이 들어있다.

FileReader() API를 사용해 미리보기를 띄워줄 수 있지.

reader.onloadend 함수에 이벤트리스너를 달아서 result값으로 이미지파일 값을 얻고나서,

img src로 쓰면 됨. setAttachment 값으로 지정해주자.

 

onClearPhoto는 파일업로드 취소 버튼 코드~

 


return HTML 부분 form 태그

1번 input은 트윗 작성란 --> 이 부분 따로 글 포스팅 예정

2번 input은 사진 업로드

            <form onSubmit={onSubmit}>
                <input 
                    value={ rweet }
                    onChange = { onChange } 
                    type="text" 
                    placeholder="What's on your mind?" 
                    maxLength={120} 
                />
                <input type="file" accept="image/*" onChange={ onFileChange } />    
                <input type="submit" value="rweet"/>
                { attachment && 
                    <div>
                        <img src={ attachment } width="50px" height="50px" />
                        <button onClick={ onClearPhoto }> ✖ </button>
                    </div>
                }
            </form>

{ attachment값이 들어오면 미리보기를 위한 div를 띄워줌. 이미지 src는 위에서 얻은 이미지 값 }

Comments