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

คุณจะต้องใช้FileReaderออบเจ็กต์เพื่อรับข้อมูล base64 และนำไปใช้กับแหล่งที่มาของแท็กรูปภาพ

นอกจากนี้ฉันไม่เห็นความจำเป็นใด ๆ ที่จะต้องทำสิ่งนี้ให้เป็น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" />