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" />
}

これが私の状態と入力のchangeメソッドのハンドルです:

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データを取得し、それをimageタグのソースに適用するには、オブジェクトを使用する必要があります。

また、これが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" />