在React中使用react dnd库上传文件功能

问题描述

我想在React中使用React dnd创建一个文件上传功能用户可以通过将文件放在div中来上传文件

解决方法

您好,我建议采用此解决方案-

  <div
    className="file-select"
    onDragOver={dragOver}
    onDragEnter={dragEnter}
    onDragLeave={dragLeave}
    onDrop={fileDrop}
    onClick={fileInputClicked}
  >
    <h4>Select File</h4>
    <input
      ref={fileInputRef}
      className="file-input"
      type="file"
      multiple
      onChange={filesSelected}
    />
  </div>

还建议使用ref:

const fileInputRef = useRef();

这只是骨架-您需要实现这些方法- 考虑验证-支持哪些文件等。

此外,您可以实施文件预览,删除等操作-因此,在这种情况下,解决方案的设计或至少是重要的


例如,我使用此功能进行多项选择:

  const [selectedFiles,setSelectedFiles] = useState([]);
  const [validFiles,setValidFiles] = useState([]);
  const [unsupportedFiles,setUnsupportedFiles] = useState([]);

  const filesSelected = () => {
    if (fileInputRef.current.files.length) {
      handleFiles(fileInputRef.current.files);
    }
  };

  const handleFiles = (files) => {
    for (let i = 0; i < files.length; i++) {
      if (validateFile(files[i])) {
        setSelectedFiles((prevArray) => [...prevArray,files[i]]);
      } else {
        files[i].invalid = true;
        setSelectedFiles((prevArray) => [...prevArray,files[i]]);
        setErrorMessage('File type not permitted');
        setUnsupportedFiles((prevArray) => [...prevArray,files[i]]);
      }
    }
    handleFileData(files);
  };
,

您可以为此使用react dropzone软件包。

npm install --save react-dropzone

或:

yarn add react-dropzone

使用挂钩的示例代码段

import React,{useCallback} from 'react'
import {useDropzone} from 'react-dropzone'
 
function MyDropzone() {
  const onDrop = useCallback(acceptedFiles => {
    // Do something with the files
  },[])
  const {getRootProps,getInputProps,isDragActive} = useDropzone({onDrop})
 
  return (
    <div {...getRootProps()}>
      <input {...getInputProps()} />
      {
        isDragActive ?
          <p>Drop the files here ...</p> :
          <p>Drag 'n' drop some files here,or click to select files</p>
      }
    </div>
  )
}

使用包装器组件的示例代码段

import React from 'react'
import Dropzone from 'react-dropzone'
 
<Dropzone onDrop={acceptedFiles => console.log(acceptedFiles)}>
  {({getRootProps,getInputProps}) => (
    <section>
      <div {...getRootProps()}>
        <input {...getInputProps()} />
        <p>Drag 'n' drop some files here,or click to select files</p>
      </div>
    </section>
  )}
</Dropzone>

使用onDrop的回调,您可以获取包含文件的acceptedFiles数组。您还可以限制大小,允许多个或仅一个和一种类型的文件来接受。

下面的示例代码段允许多张图片提供10MB的空间,并且仅允许扩展png,jpg,jpeg。

<Dropzone 
 multiple={true}
 minSize={0}
 maxSize={10485760}
 accept="image/png,image/jpg,image/jpeg"
 onDrop={acceptedFiles => console.log(acceptedFiles)}>
      {({getRootProps,getInputProps}) => (
        <section>
          <div {...getRootProps()}>
            <input {...getInputProps()} />
            <p>Drag 'n' drop some files here,or click to select files</p>
          </div>
        </section>
      )}
    </Dropzone>
,

签出react-uploady-upload-drop-zone

您可以从很少的代码开始,像这样:

import Uploady from "@rpldy/uploady";
import UploadDropZone from "@rpldy/upload-drop-zone";

const App = () => (
    <Uploady destination={{url: "https://my-server.com/upload"}}>
        <UploadDropZone onDragOverClassName="drag-over">
            <span>Drag&Drop File(s) Here</span>            
        </UploadDropZone>
    </Uploady>);

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...