React.js 입력 유형 파일로 이미지 미리보기

Aug 19 2020

현재 이미지 파일을 업로드 할 때 이미지를 미리 보려고합니다. 이미지 및 콘솔 로그를 수신 할 수 있지만 img 태그에 표시 할 수 없습니다.

렌더링하려는 방법은 다음과 같습니다.

<input type='file' id="uploadImage" onChange={this.handleImageChange} className="upload-input" />
<label htmlFor="uploadImage" className="upload-image-button">Choose An Image</label>
{this.state.imagePreview[0] ?
  <img src={this.state.imagePreview[0]} alt="" className="image-preview" /> 
  :
  <img alt="" className="image-preview" />
}

다음은 입력에 대한 변경 방법에 대한 내 상태와 핸들입니다.

state = {
  imagePreview: {}
}

handleImageChange = async (e) => {
  console.log(e.target.files)
  await this.setState({ imagePreview: e.target.files })
  console.log(this.state.imagePreview)
}

파일에 대한 내 콘솔 로그는 다음과 같습니다. 여기에 이미지 설명 입력

답변

silencedogood Aug 19 2020 at 00:08

FileReaderbase64 데이터를 가져 와서 이미지 태그의 소스에 적용하려면 객체 를 사용해야합니다 .

또한 이것이 async함수 가 될 필요가 없다고 생각 합니다 (간결성을 위해 작업중인 약속을 생략하지 않는 한).

제시 한 코드에서 다음과 같이 작동합니다.

handleImageChange(event) {

   const file = event.target.files[0];
   const reader = new FileReader();

   reader.onload = function(event) {
     // The file's text will be printed here, if you want to see the base64
     console.log(event.target.result)
     // Set state with base64 data
     this.setState({ imagePreview: e.target.result })
   };

   reader.readAsText(file);
}

HTML (또는 jsx)은 다음과 같습니다.

<img src={this.state.imagePreview} alt="" className="image-preview" />