将React Dropzone Uploader与自定义输入字段一起使用

时间:2019-08-09 21:54:04

标签: reactjs file-upload dropzone react-dropzone

我可以将输入集成到react dropzone上载器中吗?基本上,我从输入中获取的文件应该转到dropzone上传器。

反应文件放置区:https://github.com/fortana-co/react-dropzone-uploader

<Dropzone
    maxFiles={1}
    accept="image/*"
    getUploadParams={getUploadParams}
    onChangeStatus={handleChangeStatus}
    multiple={false}
    ref={setInputEl}
>
    <input
        ref={setInputEl}
        accept="image/*"
        className={classes.input}
        id="icon-button-file"
        type="file"
        onChange={handleFileChange}
    />
</Dropzone>

1 个答案:

答案 0 :(得分:1)

是的。

来自the official live examples

// https://github.com/quarklemotion/html5-file-selector
import { getDroppedOrSelectedFiles } from 'html5-file-selector'

const CustomInput = () => {
  const handleSubmit = (files, allFiles) => {
    console.log(files.map(f => f.meta))
    allFiles.forEach(f => f.remove())
  }

  const getFilesFromEvent = e => {
    return new Promise(resolve => {
      getDroppedOrSelectedFiles(e).then(chosenFiles => {
        resolve(chosenFiles.map(f => f.fileObject))
      })
    })
  }

  return (
    <Dropzone
      accept="image/*,audio/*,video/*,.pdf"
      getUploadParams={() => ({ url: 'https://httpbin.org/post' })}
      onSubmit={handleSubmit}
      InputComponent={Input}
      getFilesFromEvent={getFilesFromEvent}
    />
  )
}

Input是您提供的自定义组件:

const Input = ({ accept, onFiles, files, getFilesFromEvent }) => {
  const text = files.length > 0 ? 'Add more files' : 'Choose files'

  return (
    <label style={{ backgroundColor: '#007bff', color: '#fff', cursor: 'pointer', padding: 15, borderRadius: 3 }}>
      {text}
      <input
        style={{ display: 'none' }}
        type="file"
        accept={accept}
        multiple
        onChange={e => {
          getFilesFromEvent(e).then(chosenFiles => {
            onFiles(chosenFiles)
          })
        }}
      />
    </label>
  )
}

要说明这与您的代码有何不同:您仅添加了自定义<input>作为<Dropzone>的子级。您需要执行上述操作,以便将两者正确“连接”在一起。