Giter Club home page Giter Club logo

attr-accept's Introduction

react-dropzone logo

react-dropzone

npm Tests codecov Open Collective Backers Open Collective Sponsors Gitpod Contributor Covenant

Simple React hook to create a HTML5-compliant drag'n'drop zone for files.

Documentation and examples at https://react-dropzone.js.org. Source code at https://github.com/react-dropzone/react-dropzone/.

Installation

Install it from npm and include it in your React build process (using Webpack, Browserify, etc).

npm install --save react-dropzone

or:

yarn add react-dropzone

Usage

You can either use the hook:

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>
  )
}

Or the wrapper component for the hook:

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>

If you want to access file contents you have to use the FileReader API:

import React, {useCallback} from 'react'
import {useDropzone} from 'react-dropzone'

function MyDropzone() {
  const onDrop = useCallback((acceptedFiles) => {
    acceptedFiles.forEach((file) => {
      const reader = new FileReader()

      reader.onabort = () => console.log('file reading was aborted')
      reader.onerror = () => console.log('file reading has failed')
      reader.onload = () => {
      // Do whatever you want with the file contents
        const binaryStr = reader.result
        console.log(binaryStr)
      }
      reader.readAsArrayBuffer(file)
    })
    
  }, [])
  const {getRootProps, getInputProps} = useDropzone({onDrop})

  return (
    <div {...getRootProps()}>
      <input {...getInputProps()} />
      <p>Drag 'n' drop some files here, or click to select files</p>
    </div>
  )
}

Dropzone Props Getters

The dropzone property getters are just two functions that return objects with properties which you need to use to create the drag 'n' drop zone. The root properties can be applied to whatever element you want, whereas the input properties must be applied to an <input>:

import React from 'react'
import {useDropzone} from 'react-dropzone'

function MyDropzone() {
  const {getRootProps, getInputProps} = useDropzone()

  return (
    <div {...getRootProps()}>
      <input {...getInputProps()} />
      <p>Drag 'n' drop some files here, or click to select files</p>
    </div>
  )
}

Note that whatever other props you want to add to the element where the props from getRootProps() are set, you should always pass them through that function rather than applying them on the element itself. This is in order to avoid your props being overridden (or overriding the props returned by getRootProps()):

<div
  {...getRootProps({
    onClick: event => console.log(event),
    role: 'button',
    'aria-label': 'drag and drop area',
    ...
  })}
/>

In the example above, the provided {onClick} handler will be invoked before the internal one, therefore, internal callbacks can be prevented by simply using stopPropagation. See Events for more examples.

Important: if you omit rendering an <input> and/or binding the props from getInputProps(), opening a file dialog will not be possible.

Refs

Both getRootProps and getInputProps accept a custom refKey (defaults to ref) as one of the attributes passed down in the parameter.

This can be useful when the element you're trying to apply the props from either one of those fns does not expose a reference to the element, e.g:

import React from 'react'
import {useDropzone} from 'react-dropzone'
// NOTE: After v4.0.0, styled components exposes a ref using forwardRef,
// therefore, no need for using innerRef as refKey
import styled from 'styled-components'

const StyledDiv = styled.div`
  // Some styling here
`
function Example() {
  const {getRootProps, getInputProps} = useDropzone()
  <StyledDiv {...getRootProps({ refKey: 'innerRef' })}>
    <input {...getInputProps()} />
    <p>Drag 'n' drop some files here, or click to select files</p>
  </StyledDiv>
}

If you're working with Material UI v4 and would like to apply the root props on some component that does not expose a ref, use RootRef:

import React from 'react'
import {useDropzone} from 'react-dropzone'
import RootRef from '@material-ui/core/RootRef'

function PaperDropzone() {
  const {getRootProps, getInputProps} = useDropzone()
  const {ref, ...rootProps} = getRootProps()

  <RootRef rootRef={ref}>
    <Paper {...rootProps}>
      <input {...getInputProps()} />
      <p>Drag 'n' drop some files here, or click to select files</p>
    </Paper>
  </RootRef>
}

IMPORTANT: do not set the ref prop on the elements where getRootProps()/getInputProps() props are set, instead, get the refs from the hook itself:

import React from 'react'
import {useDropzone} from 'react-dropzone'

function Refs() {
  const {
    getRootProps,
    getInputProps,
    rootRef, // Ref to the `<div>`
    inputRef // Ref to the `<input>`
  } = useDropzone()
  <div {...getRootProps()}>
    <input {...getInputProps()} />
    <p>Drag 'n' drop some files here, or click to select files</p>
  </div>
}

If you're using the <Dropzone> component, though, you can set the ref prop on the component itself which will expose the {open} prop that can be used to open the file dialog programmatically:

import React, {createRef} from 'react'
import Dropzone from 'react-dropzone'

const dropzoneRef = createRef()

<Dropzone ref={dropzoneRef}>
  {({getRootProps, getInputProps}) => (
    <div {...getRootProps()}>
      <input {...getInputProps()} />
      <p>Drag 'n' drop some files here, or click to select files</p>
    </div>
  )}
</Dropzone>

dropzoneRef.open()

Testing

react-dropzone makes some of its drag 'n' drop callbacks asynchronous to enable promise based getFilesFromEvent() functions. In order to test components that use this library, you need to use the react-testing-library:

import React from 'react'
import Dropzone from 'react-dropzone'
import {act, fireEvent, render} from '@testing-library/react'

test('invoke onDragEnter when dragenter event occurs', async () => {
  const file = new File([
    JSON.stringify({ping: true})
  ], 'ping.json', { type: 'application/json' })
  const data = mockData([file])
  const onDragEnter = jest.fn()

  const ui = (
    <Dropzone onDragEnter={onDragEnter}>
      {({ getRootProps, getInputProps }) => (
        <div {...getRootProps()}>
          <input {...getInputProps()} />
        </div>
      )}
    </Dropzone>
  )
  const { container } = render(ui)

  await act(
    () => fireEvent.dragEnter(
      container.querySelector('div'),
      data,
    )
  );
  expect(onDragEnter).toHaveBeenCalled()
})

function mockData(files) {
  return {
    dataTransfer: {
      files,
      items: files.map(file => ({
        kind: 'file',
        type: file.type,
        getAsFile: () => file
      })),
      types: ['Files']
    }
  }
}

NOTE: using Enzyme for testing is not supported at the moment, see #2011.

More examples for this can be found in react-dropzone's own test suites.

Caveats

Required React Version

React 16.8 or above is required because we use hooks (the lib itself is a hook).

File Paths

Files returned by the hook or passed as arg to the onDrop cb won't have the properties path or fullPath. For more inf check this SO question and this issue.

Not a File Uploader

This lib is not a file uploader; as such, it does not process files or provide any way to make HTTP requests to some server; if you're looking for that, checkout filepond or uppy.io.

Using <label> as Root

If you use <label> as the root element, the file dialog will be opened twice; see #1107 why. To avoid this, use noClick:

import React, {useCallback} from 'react'
import {useDropzone} from 'react-dropzone'

function MyDropzone() {
  const {getRootProps, getInputProps} = useDropzone({noClick: true})

  return (
    <label {...getRootProps()}>
      <input {...getInputProps()} />
    </label>
  )
}

Using open() on Click

If you bind a click event on an inner element and use open(), it will trigger a click on the root element too, resulting in the file dialog opening twice. To prevent this, use the noClick on the root:

import React, {useCallback} from 'react'
import {useDropzone} from 'react-dropzone'

function MyDropzone() {
  const {getRootProps, getInputProps, open} = useDropzone({noClick: true})

  return (
    <div {...getRootProps()}>
      <input {...getInputProps()} />
      <button type="button" onClick={open}>
        Open
      </button>
    </div>
  )
}

File Dialog Cancel Callback

The onFileDialogCancel() cb is unstable in most browsers, meaning, there's a good chance of it being triggered even though you have selected files.

We rely on using a timeout of 300ms after the window is focused (the window onfocus event is triggered when the file select dialog is closed) to check if any files were selected and trigger onFileDialogCancel if none were selected.

As one can imagine, this doesn't really work if there's a lot of files or large files as by the time we trigger the check, the browser is still processing the files and no onchange events are triggered yet on the input. Check #1031 for more info.

Fortunately, there's the File System Access API, which is currently a working draft and some browsers support it (see browser compatibility), that provides a reliable way to prompt the user for file selection and capture cancellation.

Also keep in mind that the FS access API can only be used in secure contexts.

NOTE You can disable using the FS access API with the useFsAccessApi property: useDropzone({useFsAccessApi: false}).

Supported Browsers

We use browserslist config to state the browser support for this lib, so check it out on browserslist.dev.

Need image editing?

React Dropzone integrates perfectly with Pintura Image Editor, creating a modern image editing experience. Pintura supports crop aspect ratios, resizing, rotating, cropping, annotating, filtering, and much more.

Checkout the Pintura integration example.

Support

Backers

Support us with a monthly donation and help us continue our activities. [Become a backer]

Sponsors

Become a sponsor and get your logo on our README on Github with a link to your site. [Become a sponsor]

Hosting

react-dropzone.js.org hosting provided by netlify.

License

MIT

attr-accept's People

Contributors

1pete avatar 777polarfox777 avatar ajsharp avatar ayal avatar edsrzf avatar gfx avatar jskorepa avatar nhalstead avatar nolski avatar octav47 avatar okonet avatar pimm avatar rolandjitsu avatar rxmarbles avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

attr-accept's Issues

ESM build?

Is your feature request related to a problem? Please describe.
When including attr-accept in an ESM library, Vite fails to properly convert from CJS to ESM. See soorria/solid-dropzone#3 for a real-world example.

Describe the solution you'd like
Offer an ESM build parallel to the current CJS options. I believe a larger Webpack configuration can do this relatively easily.

Describe alternatives you've considered
Forking just to produce our own ESM build.

Allow passing an array of mime-types

Moved from react-dropzone/react-dropzone#243

When passing in an array of mime types, it is correctly limiting available selections for the onClick file selector (non-accepted files are greyed out), but drag and drop does not work and it throws an error in the console saying that a string should be passed. Would it be possible to enable an array of mimetypes?

Add Contributing.md

The document should state

  1. the workflow,
  2. the fact this repo uses semantic-release
  3. the fact it uses angular commit messages

accept: MIME type should be case insensitive

Do you want to request a feature or report a bug?

  • I found a bug
  • I want to propose a feature

What is the current behavior?

The MIME type check with accept config is case-sensitive, but it should be case-insensitive according to SO / specs. Source: https://stackoverflow.com/a/12869287/4717408. Here is a scenario where it impacts the behavior. For an Excel file with extension .xlsm, we have the MIME types:

  • On Chrome Windows: application/vnd.ms-excel.sheet.macroEnabled.12 (upper-case E)
  • On Chrome Mac: application/vnd.ms-excel.sheet.macroenabled.12 (lower-case e)

This leads to a behavior a bit hard to understand when I develop on Windows (I have copy/pasted the official MIME type which is the first variant, so I'm not aware of the case issue) and I test later on Mac. If I'm not familiar with detailed MIME type specs like being case-sensitive or not, or different platforms providing different cases, it will take some time before I find the source cause.

If the current behavior is a bug, please provide the steps to reproduce.

Sandbox: https://codesandbox.io/s/vigilant-curran-jqxwi

  1. provide accept: "application/vnd.ms-excel.sheet.macroEnabled.12" MIME type filter
  2. Try on Windows: it works (you can upload .xlsm Excel files)
  3. Try on Mac: it does NOT work. Reason: the MIME type on Mac is application/vnd.ms-excel.sheet.macroenabled.12 (lower-case e)

What is the expected behavior?

The MIME type should be case-insensitive, so providing any case in the accept config should work.

Please mention other relevant information such as the browser version, Operating System and react-dropzone version.

Chrome, latest version on Windows and Mac

The current workaround is to provide both cases in the list of accepted MIME types: https://codesandbox.io/s/agitated-night-52c6b


Issue initially created here

Btw, thanks for this great lib!


[Edit] Here is the PR: #51

Accept custom extensions like html file input

In <input type='file'>, the fact that you can use the accept prop for random extensions (like accept='myext') is rather handy for all those that create and use proprietary file types.

Getting into react-dropzone, is it true that this example by @export-mike (copied below) is currently the best shot?

Pseudo code:

< ... accept="" onDrop={file => {
 if(!file.name.endsWith('.csv')) { this.setState({ rejected: true }) }
 // doSomething();
} >

Are there any plans for extending the accept prop in the same way file inputs work? When users browse files, it's nice to have them filtered by the extension(s) that'll work.

Thank you!

The automated release is failing 🚨

🚨 The automated release from the master branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you could benefit from your bug fixes and new features.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can resolve this 💪.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here is some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


Invalid npm token.

The npm token configured in the NPM_TOKEN environment variable must be a valid token allowing to publish to the registry https://registry.npmjs.org/.

If you are using Two-Factor Authentication, make configure the auth-only level is supported. semantic-release cannot publish with the default auth-and-writes level.

Please make sure to set the NPM_TOKEN environment variable in your CI with the exact value of the npm token.


Good luck with your project ✨

Your semantic-release bot 📦🚀

Certain file types are not allowed

Per this issue in react-dropzone
It seems the check on file types has been changed in browser support as it makes those that have a filetype that includes a . to a blank string. The example here is a .stl file. This is an example file from a basic input file type tag

File(7138484) {name: "Apollo_11.stl", lastModified: 1440523936000, lastModifiedDate: Tue Aug 25 2015 10:32:16 GMT-0700 (Mountain Standard Time), webkitRelativePath: "", size: 7138484, …}
lastModified
:
1440523936000
lastModifiedDate
:
Tue Aug 25 2015 10:32:16 GMT-0700 (Mountain Standard Time) {}
name
:
"Apollo_11.stl"
size
:
7138484
type
:
"model/x.stl-binary"
webkitRelativePath
:
""
__proto__
:
File

Last fix was not published on npm

It seems like 5d4cdf8 was not published on npm due to some error on Travis:

after_success
1.36s$ travis-deploy-once "npm install -g semantic-release@13 && semantic-release"
{ HTTPError: Response code 403 (Forbidden)
    at stream.catch.then.data (/home/travis/build/react-dropzone/attr-accept/node_modules/got/index.js:341:13)
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:189:7)
  name: 'HTTPError',
  host: 'api.travis-ci.org',
  hostname: 'api.travis-ci.org',
  method: 'POST',
  path: '/auth/github',
  protocol: 'https:',
  url: 'https://api.travis-ci.org/auth/github',
  statusCode: 403,
  statusMessage: 'Forbidden',
  headers: 
   { connection: 'close',
     server: 'nginx',
     date: 'Sat, 12 Oct 2019 05:22:35 GMT',
     'content-type': 'application/json',
     'transfer-encoding': 'chunked',
     'strict-transport-security': 'max-age=31536000',
     'x-endpoint': 'Travis::Api::App::Endpoint::Authorization',
     'x-pattern': '/github',
     'x-oauth-scopes': 'public',
     'x-accepted-oauth-scopes': 'public',
     vary: 'Accept,Accept-Encoding',
     'content-encoding': 'gzip',
     'x-rack-cache': 'invalidate, pass',
     'x-request-id': '117769e9-6c3a-414c-b2c5-f54c1bcba3a1',
     'access-control-allow-origin': '*',
     'access-control-allow-credentials': 'true',
     'access-control-expose-headers': 'Content-Type, Cache-Control, Expires, Etag, Last-Modified, X-Request-ID',
     via: '1.1 vegur' } }

Is it possible that we're missing some token or whatever token we used expired?

This change would probably also fix react-dropzone/react-dropzone#887.

Feature Request: Split into two functions: getMimeType() + validateMimeType()

I'd like to use this same lib not only for validation, but determining which type a given file is as well.

Signatures

function getMimeType(file?: File): { baseType, type } {
  ...
}

function validateMimeType(file?: File, acceptedFiles?: string | string[]): boolean {
  ...
  const { baseType, type } = getMimeType(file)
  ...
}

Sample Usage

const myFile = <a file>

if (!validateMimeType(myFile)) { throw new Error('not a valid file type') }

if (getMimeType(myFile).baseType === 'image') {
  // present preview of the image
} else {
  // present a generic file icon
}

xls上传失败

application/vnd.ms-excel不能上传.xls文件,判断过不了

support require('attr-accept');

not big issue but could it support

const attrAccept = require('attr-accept');

instead of

const attrAccept = require('attr-accept').default;

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.