Coder Social home page Coder Social logo

file-selector'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

file-selector's People

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

Watchers

 avatar  avatar

file-selector's Issues

Different file objects returned when same file is dropped directly vs dropped via nested folder.

As discussed in #7, when we drop a .docx file directly on a Dropzone we have no issues. When we drop a folder that contains the same .docx file, the file object is somehow different which results in downstream mimetype issues. The reason we believe this is an issue with file-selector/react-dropzone is that the following work around solves our problem:

before:

onDrop={this.handleAddFiles}

after:

onDrop={(newFiles) => {
    const modifiedFiles = newFiles.map(f => {
        const modifiedFile = new File([f], f.name, { type: f.type });
        modifiedFile.path = f.path;
        return modifiedFile;
    });
    this.handleAddFiles(modifiedFiles);
}}

Note: we do not have issues with all file types. For example, PDFs seem unaffected by the symptom.

[BUG] File-selector interface error(TS2430) on electron

Describe the bug
TS2430 on file-selector interface

To Reproduce

Expected behavior
None
Screenshots

스크린샷 2022-07-12 오후 1 50 05

node_modules/file-selector/dist/file.d.ts:3:18 - error TS2430: Interface 'FileWithPath' incorrectly extends interface 'File'.
  Types of property 'path' are incompatible.
    Type 'string | undefined' is not assignable to type 'string'.
      Type 'undefined' is not assignable to type 'string'.
3 export interface FileWithPath extends File {
                 ~~~~~~~~~~~~

Desktop (please complete the following information):

  • OS: [Ubuntu-latest]
  • Browser [Electron]
  • Version [0.6.0]

Additional context
In the meantime, I've added this setting to tsconfig.json to suppress this error by

{
  "compilerOptions": {
    "skipLibCheck": true,
    ...
}

However, I wrote an issue because it is a bug that needs to be solved one day.

Word document file objects missing `type` in Chrome

Using in conjunction with react-dropzone, when dropping a word document into a Dropzone configured to use the getDataTransferItems={evt => fromEvent(evt)}, the accepted files have type="" in Google Chrome (the type is not stripped in Firefox).

After debugging, it appears that the result of the FileSystemFileEntry file method is missing type for doc/docx in Chrome.

Easiest short-term fix is to add doc and docx to the COMMON_MIME_TYPES.

Build source maps points to srcc/**.ts but src is not included in final bundle

Using via react-dropzone,
v0.2.2

Source maps points to src/* files but src/* is not included. Should either be set to inline-sourcemaps or include the src or don't provide sourcemaps in final build.

dist/es5/index.js.map:1
"sourceRoot":"","sources":["../../src/index.ts"]

What is the current behavior?
"app: Failed to parse source map from '\node_modules\file-selector\src\file-selector.ts' file: Error: ENOENT: no such file or directory, open '***\node_modules\file-selector\src\file-selector.ts'"

[ENHANCEMENT] Is possible that you share this component for Denojs?

Is your feature request related to a problem? Please describe.
I'm starting with Denojs and your library is very powerful and simple, but I can't use that directly in Denojs

Describe the solution you'd like
Will very good if you share you code for anywhere in version ES module (import/export), I currently use your library with [unpkg](https://unpkg.com/[email protected]/dist/bundles/file-selector.umd.min.js but isn't the same standar 😭

Describe alternatives you've considered
You can share in Skypack or denoland for example and it is very simple. the deno community will very grateful with you

[BUG] v0.4.0 returning empty value as file path in electron

Describe the bug
In my project I have updated react-dropzone from v11.5.1 to v12.0.0.
Since then the path key of the file returned by react-dropzone is empty:
empty_path_returned

I once had similar issues. So I checked the version of file-selector used using yarn why file-selector. It returns:

  • 0.2.4 in react-dropzone v11.5.1

024

  • 0.4.0 in react-dropzone v12.0.0

040

I have repeatedly up/downgraded react-dropzone versions and this issue consistently occurs on v12.0.0/0.4.0.

I tried installing react-dropzone v12.0.0 while enforcing file-selector v0.2.4 using yarn resolutions. That did not work as no file was returned from react-dropzone (also no error occured). So it seems I have to stay on react-dropzone v11.5.1 for now.

To Reproduce
I would have to build a minimal electron app to demonstrate this.

Expected behavior
The full path should be returned as it did in previous versions.

Desktop:

  • OS: Windows 11
  • electron v17.0.0

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.


No npm token specified.

An npm token must be created and set in the NPM_TOKEN environment variable on your CI environment.

Please make sure to create an npm token and to set it in the NPM_TOKEN environment variable on your CI environment. The token must allow to publish to the registry https://registry.npmjs.org/.


Good luck with your project ✨

Your semantic-release bot 📦🚀

Include LICENSE file in distribution

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?
No LICENSE file is included in distribution
If the current behavior is a bug, please provide the steps to reproduce.

What is the expected behavior?
I expect LICENSE file to be included in distribution
If this is a feature request, what is motivation or use case for changing the behavior?

Other info

[BUG] Cannot Drag/drop email from Outlook on Safari

Describe the bug
Dear,
In my project, I usually move email from outlook to the web.
It doesn't work when I drag an email from outlook and drop it on 'drop-zone'. But it works with this same behavior with Chrome and FF. Seem dataTransfer.files are empty on Safari.

To Reproduce
Just drop an email from outlook to dropzone

Expected behavior
Able to support drag/drop the email from outlook on safari like other browsers

Screenshots

Desktop (please complete the following information):

  • OS: macOS
  • Browser: safari
  • Version: Version 15.1

Thanks

[ENHANCEMENT] Always populate a relativePath property

Is your feature request related to a problem? Please describe.
I have built an app that has a file system/structure. When I drag and drop a folder I need to create the Folder, all sub folders and files. This works fine in the browser but breaks in my electron app.

Describe the solution you'd like
Always populate a relativePath property regardless of whether the {path} property exists or not.

Describe alternatives you've considered
I thought about just making it always set the path to the relative path. Although this would be okay for my use case, I don't know if other developers are dependent on knowing the absolute path in an electron app.

Additional context
This is really important as I have a production application that is behaving unexpectedly in the electron app. I have already made the necessary changes locally. Happy to discuss the solution with you.

Non-enumerable type field on file when dropping parent folder containing .docx file

react-dropzone version: v0.1.8
browser: Chrome Version 72.0.3626.119

The change from v0.1.7 → v0.1.8 (and still broken in v0.1.9) appears to have broken the file type field returned on nested files when dropping a folder containing .docx files (it does not appear to effect all file types such as .pdf files).

In v0.1.8, when we drop a .docx file directly onto a Dropzone the file has the correct type field and everything works as expected. When we drop a folder containing the same file, the type field is 'non-enumarble/'greyed out' screenshot.

In our specific case, this prevents the file type from being set when we upload the file object with axios which results in validation errors.

react-dropzone v8.2.0 returns only file name in path property in electron, not the path

The files Objects returned on onDrop used to return the entire file path in the path property. Sinse v8.2.0 not any more.

The path property should contain the entire path, just as it does in v8.1.0.

According to react-dropzone/react-dropzone#769 (comment) the issue lies in file-selector.

Last tested with react-dropzone v10.0.4 that according to

$ yarn list --pattern file-selector
yarn list v1.13.0
└─ [email protected]
Done in 3.56s.

contains file-selector v0.1.11

LICENSE file

Could you add the LICENSE file to the repo and to the npm package? Otherwise some companies cannot use this package due to the legal reasons.
Thank you!

Webpack build fails with 0.1.16

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?

My webpack build is failing with the following error message when using the latest 0.1 version of file-selector (0.1.16):

ERROR in ./node_modules/react-dropzone/dist/es/index.js
Module not found: Error: Can't resolve 'file-selector' in '/home/daniel/Development/sulu/sulu/node_modules/react-dropzone/dist/es'
 @ ./node_modules/react-dropzone/dist/es/index.js 30:0-42 378:61-70
 @ ./src/Sulu/Bundle/MediaBundle/Resources/js/components/SingleMediaDropzone/SingleMediaDropzone.js
 @ ./src/Sulu/Bundle/MediaBundle/Resources/js/components/SingleMediaDropzone/index.js
 @ ./src/Sulu/Bundle/MediaBundle/Resources/js/containers/SingleMediaUpload/SingleMediaUpload.js
 @ ./src/Sulu/Bundle/MediaBundle/Resources/js/containers/SingleMediaUpload/index.js
 @ ./src/Sulu/Bundle/MediaBundle/Resources/js/containers/Form/fields/SingleMediaUpload.js
 @ ./src/Sulu/Bundle/MediaBundle/Resources/js/containers/Form/index.js
 @ ./src/Sulu/Bundle/MediaBundle/Resources/js/index.js
 @ ./index.js                                     
 @ multi ./index.js

After downgrading to file-selector 0.1.13 the build is working again.

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

  1. Make sure version 0.1.16 is installed
  2. Build your application using webpack
  3. See the error from above

What is the expected behavior?

The build should still be working.

Please update package.json for v0.1.x seriese as well

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?

Some projects refer to file-selector by specifying semver like ^0.1.12 (e.g. https://github.com/react-dropzone/react-dropzone/blob/master/package.json). v0.1.16 is missing required dist folder.

  1. Add file-selector to package.json
    $ cat package.json
    {
        "dependencies": {
            "file-selector": "^0.1.12"
        }
    }
    
  2. npm install
  3. 0.1.16 is installed and dist is missing.
    $ cat package-lock.json
    {
        "requires": true,
        "lockfileVersion": 1,
        "dependencies": {
            "file-selector": {
                "version": "0.1.16",
                "resolved": "https://registry.npmjs.org/file-selector/-/file-selector-0.1.16.tgz",
                "integrity": "sha512-QM6Y0UlCv8AhMu6sNfrd5CkGlGx0qBtmN+J2Z71ymgiQF4PO3gFrw8phaloNZJA0XGtlXAvpFaSBy4g0vdsPnQ==",
                "requires": {
                    "tslib": "^2.0.1"
                }
            },
            "tslib": {
                "version": "2.0.3",
                "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.0.3.tgz",
                "integrity": "sha512-uZtkfKblCEQtZKBF6EBXVZeQNl82yqtDQdv+eck8u7tdPxjLu2/lp5/uPW+um2tpuxINHWy3GhiccY7QgEaVHQ=="
            }
        }
    }
    
    $ ls node_modules/file-selector/ -A
    LICENSE  README.md  package.json
    

The same fixes done on 0.2.x (9b57a12#diff-7ae45ad102eab3b6d7e7896acd08c427a9b25b346470d7bc6507b6481575d519, 9b3bbb1) would be required for these clients.

What is the expected behavior?

Required folders should be included.

$ ls -A node_modules/file-selector/
CHANGELOG.md  README.md  dist  package.json  src

Path missing when uploading directory

When using file selector fromEvent handler on <input {..properties} type='file' webkitdirectory='true' /> full path is missing.

This is example from dropzone event getDataTransferItems={e => fromEvent(e)}:

File(106182)
  lastModified: 1538560178310
  lastModifiedDate: Wed Oct 03 2018 11:49:38 GMT+0200 (czas środkowoeuropejski letni) {}
  name : "audit-with-purge.png"
  size: 106182
  type: "image/png"
  webkitRelativePath: ""
  path: "/test/audit-with-purge.png"

And this is from input onChange event with fromEvent handler:

File(106182)
  lastModified: 1538560178310
  lastModifiedDate: Wed Oct 03 2018 11:49:38 GMT+0200 (czas środkowoeuropejski letni) {}
  name: "audit-with-purge.png"
  size: 106182
  type: "image/png"
  webkitRelativePath: ""
  path: "audit-with-purge.png"

Is there a way to preserve full path ?

EDIT:
In version 0.1.8 onChange actually adds webkitRelativePath, but path is still different and missing full path compared to one from getDataTransferItems

File path is file name

Hello!

I am attempting to take a docx file and convert it into a pdf.
In order to do that I need the uploaded/"dropped" file path as the function's first parameter.

When I console.log the file object's path it just returns the name. Any recommendations?

Thanks.

Screen Shot 2019-12-16 at 8 10 26 AM

mime-type empty in react-dropzone

Hello,

I have a react dropzone with accept condition on Excel file but sometimes MIME-type is empty and all files are rejected. (The problem seems to be random)
Do you think it is possible to use something like https://github.com/jshttp/mime-types or https://github.com/jshttp/mime-db to determine the MIME type of the files and avoid these problems of rejected files ?

PS : The fastest solution would be to add it in COMMON_MIME_TYPES but maybe using mime-db instead of COMMON_MIME_TYPES is better to do it only once.

Thank you

Interface 'FileWithPath' incorrectly extends 'File'

node_modules/file-selector/dist/file.d.ts:3:18 - error TS2430: Interface 'FileWithPath' incorrectly extends interface 'File'.
  Types of property 'path' are incompatible.
    Type 'string | undefined' is not assignable to type 'string'.
      Type 'undefined' is not assignable to type 'string'.

export interface FileWithPath extends File {
                   ~~~~~~~~~~~~

Introduce an option to ignore a File's absolute path in an Electron environment

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?

When running in a browser environment, the native File object contains no path (a path is added by toFileWithPath)
When running in an Electron environment, the native File object contains an absolute path.

https://www.electronjs.org/docs/api/file-object

Electron has added a path attribute to the File interface which exposes the file's real path on filesystem.

Because of this, file-selector skips adding a path to the File object:

if (typeof f.path !== 'string') { // on electron, path is already set to the absolute path

What is the expected behavior?

As reported in #10, this behaviour is expected by some users. However I would like the option to ignore the absolute path, and instead use the relative path provided by toFileWithPath

A new boolean paramter could be provided to toFileWithPath that determines if a file's path property should be ignored.

This boolean paramter would be false by default to prevent breaking changes.

We would also have to provide a new option in react-dropzone:
https://github.com/react-dropzone/react-dropzone/blob/1b1177daaa51d7cc542d59f32dfd1e2956b92a55/src/index.js#L68

If this is a feature request, what is motivation or use case for changing the behavior?

I would like consistency between Browser & Electron environments. I need this because I use the file's relative path to reconstruct the file's folder structure on our server.

Other info

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.