如何使用react-dropzone预览图像

Fil*_*lip 0 javascript reactjs react-hooks

我希望用户从计算机“上传”文件,将其存储在浏览器中(我猜)并显示图像,而不将其发送到服务器。基本上,我希望这种情况发生(网站上的示例): https: //www.javascripture.com/FileReader

这本身有效,但我正在使用react-dropzone,但它不起作用。

我的代码:

import React, { useCallback, useState } from "react";
import { useDropzone } from "react-dropzone";
import styles from "./dropzone.module.css";
import ImageZone from "../imagezone";

export default function Dropzone() {
  const [path, setPath] = useState("");
  const openFile = () => {
    const reader = new FileReader();
    reader.onload = () => {
      const dataURL = reader.result;
      setPath(dataURL);
    };
  };
  const onDrop = useCallback(acceptedFiles => {
    openFile();
  }, []);
  const { getRootProps, getInputProps, isDragActive } = useDropzone({ onDrop });

  return (
    <div className={styles.mycontainer}>
      <div className={styles.dropzone} {...getRootProps()}>
        <input {...getInputProps()} />
        {isDragActive ? (
          <p>Drop the files here ...</p>
        ) : (
          <p>Drag 'n' drop some files here, or click to select files</p>
        )}
      </div>
      <ImageZone src={path}></ImageZone>
    </div>
  );
}

Run Code Online (Sandbox Code Playgroud)

tom*_*mfa 5

用于从 onDrop 回调返回的文件URL.createObjectURL(file)

import React, { useCallback, useState } from "react";
import { useDropzone } from "react-dropzone";

export default function Dropzone() {
  const [paths, setPaths] = useState([]);

  const onDrop = useCallback(acceptedFiles => {
    setPaths(acceptedFiles.map(file => URL.createObjectURL(file));
  }, [setPaths]);
  const { getRootProps, getInputProps, isDragActive } = useDropzone({ onDrop });

  return (
    <div>
      <div {...getRootProps()}>
        <input {...getInputProps()} />
        <p>Drop the files here ...</p>
      </div>
      {paths.map(path => 
        <img key={path} src={path} />
       }
    </div>
  );
}
Run Code Online (Sandbox Code Playgroud)

请参阅https://react-dropzone.js.org/#!/Previews了解更多信息。