文件上传器不显示图片

File uploader isn't showing the picture

我有问题。我正在创建一个小型文件上传器,用于上传照片。如果用户按下图标,就会出现一个文件上传器,然后他就可以 select 一张照片。在 selecting 之后,照片没有显示。具体问题出在哪里?

import React, { useState } from 'react';

const Profilpic = () => {
  const [preview, setPreview] = useState(null);

  const fileSelectedHandler = (event) => {
    console.log(event.target.files[0]);
    if (event.target.files[0].size > 71680) {
      alert('File is too big! Wie Samys Dick');
    } else {
      setPreview(event.target.files[0]);
    }
  };

  return (
    <div>
      {preview ? (
        <img src={preview} alt="Preview" width="150px" height="150px" />
      ) : (
        <div>
          <label htmlFor="myInput">
            <i className="fas fa-user-circle"></i>
          </label>
          <input
            id="myInput"
            style={{ display: 'none' }}
            type={'file'}
            onChange={fileSelectedHandler}
          />
        </div>
      )}
    </div>
  );
};

export default Profilpic;

首先从input标签中去掉style标签 然后用

替换函数
const fileSelectedHandler = (event) => {
    console.log(event.target.files[0]);

    if (event.target.files[0].size > 71680) {
      alert("File is too big! Wie Samys Dick");
    } else {
      const reader = new FileReader();

      reader.readAsDataURL(event.target.files[0]);
      reader.onloadend = () => {
        setPreview(reader.result);
      };
    }
  };

这对你有用。您只需为所选图片创建 URL。

import { useState } from "react";
import "./styles.css";

export default function App() {
  const [preview, setPreview] = useState(null);

  const fileSelectedHandler = (event) => {
    console.log(event.target.files[0]);
    if (event.target.files[0].size > 71680) {
      alert("File is too big! Wie Samys Dick");
    } else {
      let img = URL.createObjectURL(event.target.files[0]);
      setPreview(img);
    }
  };

  console.log(preview);

  return (
    <div>
      {preview ? (
        <img src={preview} alt="Preview" />
          ) : (
        <input id="myInput" type="file" onChange={fileSelectedHandler} />
      )}
    </div>
  );
}