【问题标题】:How can I show an image in the website of a react application, right after a user uploads it?如何在用户上传后立即在 React 应用程序的网站上显示图像?
【发布时间】:2021-11-09 06:39:00
【问题描述】:

这是场景:用户必须上传一个文件,一旦他上传了,我想在服务器收到它后立即将它显示在页面上。 我尝试了条件渲染,但这不起作用。

我应该怎么做才能让它工作?提前致谢。

代码:

import React, { useState } from 'react'

import './App.css'

function App() {
  const [image, setImage] = useState('')

  const submitHandle = (e) => {
    if (!image) {
      console.log('please upload an image')
    } else {
      console.log(e.target)

      e.preventDefault()
      console.log('submitted')
    }
  }

  return (
    <section>
      <div>
        <div>
          <h1>heading one</h1>
          <form onSubmit={submitHandle}>
            <input
              value={image}
              onChange={(e) => setImage(e.target.value)}
              type='file'
              accept='image/gif, image/jpeg, image/png'
            />
            <button type='submit'>submit</button>
          </form>
          {image && <img src={image} alt='image' />}
        </div>
      </div>
    </section>
  )
}

export default App

【问题讨论】:

    标签: javascript reactjs file-upload


    【解决方案1】:

    对于file 类型的input,其值不能通过代码设置。

    要立即查看图像,您必须使用 FileReader 将其转换为字符串;

    所以我们必须创建另一个函数loadImage 并将所选文件作为参数传入


    完整代码

    function App() {
      const [image, setImage] = useState('');
      
      const loadImage = (file) => {
        const reader = new FileReader();
        reader.addEventListener('load', e => setImage(e.target.result));
        reader.readAsDataURL(file);
      }
    
      const submitHandle = (e) => {
        if (!image) {
          console.log('please upload an image')
        } else {
          console.log(e.target)
    
          e.preventDefault()
          console.log('submiited')
        }
      }
    
      return (
        <section>
          <div>
            <div>
              <h1>heading one</h1>
              <form onSubmit={submitHandle}>
                <input
                  onChange={(e) => loadImage(e.target.files[0])}
                  type='file'
                  accept='image/gif, image/jpeg, image/png'
                />
                <button type='submit'>submit</button>
              </form>
              {image && <img src={image} alt='image' />}
            </div>
          </div>
        </section>
      )
    }
    

    【讨论】:

    • 感谢您的回答,但是我收到 TypeError: Cannot read properties of undefined (reading '0') 。尝试上传图片时。
    • 现在我得到 TypeError: reader.readAsDatatURL is not a function
    猜你喜欢
    • 2017-03-15
    • 1970-01-01
    • 2014-02-03
    • 2014-04-22
    • 2021-07-27
    • 1970-01-01
    • 1970-01-01
    • 2018-10-20
    • 2019-09-22
    相关资源
    最近更新 更多