[React] 파일 업로드 하기

Jayden ·2023년 8월 9일
0

1. input 태그 구현

<Wrapper marginTop={37}>
  <H4 marginBottom={8}>파일 등록</H4>
	<Label width={784} height={48} htmlFor="input-file" 
		style={{display :"inline-block",
              	color :"#8F9098",
                fontSize : "14px",
                lineHeight : "48px",
                paddingLeft : "16px",
                boxSizing : "border-box",
                position:"relative",
                borderRadius : "12px",
                border: "1px solid var(--neutral-light-darkest, #C5C6CC)"}}>
        		파일을 선택하세요<Upload right={12} top={12}/>
    </Label>
	//.jpg, .png, .pdf 형식만 업로드
      <Input 
          onChange={(e : React.ChangeEvent<HTMLInputElement>)=>handleFile(e)}
          accept=".jpg , .png, .pdf"
          id =  "input-file"
          type="file"
      />
  		<SupportText>jpg, png, pdf 확장자 등록가능</SupportText>
    </Wrapper>

2. 상태값 설정


	// 타입 설정
	interface formType {

       ...(생략)
      
        file : File | null,
          
       ...(생략)
    }
        
        
    // 상태값(초깃값) 설정
	const [form, setForm] = useState<formType>({
      
       ...(생략)
      
        file : null,
      
       ...(생략)
    
    })

3. 이벤트(파일 업로드) 함수 구현


 const handleFile = (e : React.ChangeEvent<HTMLInputElement>) => {
       
       if(e?.target.files){

       // 파일 용량 5MB로 제한하기   
           const maxSize = 5 * 1024 * 1024;
           const fileSize = e.target.files[0]?.size;
           if(fileSize > maxSize){
               alert("첨부 파일 사이즈는 5MB 이내로 등록 가능합니다.");
               return;
           }
   
   		console.log(e.target.file)
   		console.log(e.target.file[0])
   
           setForm({
               ...form,
               file : e.target.files[0]
           })
       }
   }

e.target.filee.target.file[0]을 콘솔로 확인해 보겠습니다.

e.target.file은 FileList 타입으로 유사 객체 배열입니다.

업로드한 파일의 리스트가 나옵니다.

파일들의 인덱스와 파일 정보, length를 확인할 수 있습니다.

e.target.file[0]은 File 타입입니다.

일반적으로 파일 하나만 업로드 하므로 콘솔로

console.log(e.target.file[0])

확인하면 업로드한 파일의 정보를 확인할 수 있습니다.

사실, <input type='file'>로 여러개의 파일을 업로드 할 수 있습니다.

<input type='file' multiple/>
다중 파일을 업로드 할 경우에는 e.target.file[1], e.target.file[2] 이런식으로 참조하여 파일 정보를 확인 할 수 있습니다.

덧붙여, <form>~</form>태그안에 파일 업로드가 포함될 경우, post 요청 시
content-type은 application/json이 아니고, multipart/form-data로 설정해야 합니다.

profile
프론트엔드 개발자

0개의 댓글