繁体   English   中英

如何使用 react-dropzone 预览图像

[英]How to preview an image using react-dropzone

我希望用户从他们的计算机“上传”文件,将其存储在浏览器中(我猜)并显示图像,而不将其发送到服务器。 基本上,我希望这种情况发生(网站上的示例): 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>
  );
}

您可以使用文件阅读器 api 读取拖放文件的内容,然后将其显示。 您需要修复onload回调

 const onDrop = useCallback(acceptedFiles => { const reader = new FileReader(); reader.onload = e => { const dataURL = e.target.result; setPath(dataURL); }; acceptedFiles.forEach(file => reader.readAsArrayBuffer(file)) }, []);

对从 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> ); }

有关更多信息,请参阅https://react-dropzone.js.org/#!/Previews

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM