Getting react-dropzone to accept *all* files
Asked Answered
B

5

5

I have inherited a code base that is React.JS on the front-end and Node.JS/Express.JS on the back-end on an AWS EC2 instance server. The code I have usese react-dropzone (https://react-dropzone.js.org/) and was made to just take drag&drops of image files. The product owner for the project I'm working on now wants it to accept all files (*.pdf's, *.docx, *.xlsx, etc.).

I'm wondering how to go about getting it to accept all files? I've gone through the react-dropzone docs and I've yet to find any example to show how to get it to accept all file types? Is it as simple as setting the accept="..." from accept="image/*" to accept="*/*"? can the string for accept="..." be an array, like: accept=["image/*","text/*",...], etc.? what is the correct way to get react-dropzone to accept any file type?

Here is the code for my onDrop callback —

    onDrop = (acceptedFiles, rejectedFiles) => {
      let files = acceptedFiles.map(async file => {
        let data = new FormData();
        data.append("file", file);

        let item = await axios
          .post("triage/upload", data, {
            headers: {
              "X-Requested-With": "XMLHttpRequest",
              "Content-Type": "application/x-www-form-urlencoded"
            }
          })
          .then(response => {
            return Object.assign(file, {
              preview: URL.createObjectURL(file),
              filename: response.data.filename
            });
          })
          .catch(err => {
            let rejects = rejectedFiles.map(async file => {
              let data = new FormData();
              await data.append("file", file);

              console.log("There was an error while attempting to add your files:", err);
              console.log("The files that were rejected were:\n", rejects.join('\n'))
            })
          });
        return item;
      });
      Promise.all(files)
      .then(completed => {
        console.log("completed", completed);
        let fileNames = completed.map(function(item) {
          return item["filename"];
        });
        this.setState({ files: completed, fileNames: fileNames });
      })
      .catch(err => {
        console.log('DROPZONE ERROR:', err);
      });
    };

...and here is the code for <DropZone> itself in the same file —

              <Dropzone accept="image/*" onDrop={this.onDrop}>
                {({ getRootProps, getInputProps, isDragActive }) => {
                  return (
                    <div
                      {...getRootProps()}
                      className={classNames("dropzone", {
                        "dropzone--isActive": isDragActive
                      })}
                    >
                      <input {...getInputProps()} />
                      {isDragActive ? (
                        <div>
                          <div className="centered">
                            <Icon name="cloud upload" size="big" />
                          </div>
                          <div className="centered">Drop Files Here.</div>
                          <div className="centered">
                            <Button className="drop-button">
                              Or Click to Select
                            </Button>
                          </div>
                        </div>
                      ) : (
                        <div>
                          <div className="centered">
                            <Icon name="cloud upload" size="big" />
                          </div>
                          <div className="centered">
                            Drag and Drop Supporting Files here to
                            Upload.
                          </div>
                          <div className="centered">
                            <Button className="drop-button">
                              Or Click to Select
                            </Button>
                          </div>
                        </div>
                      )}
                    </div>
                  );
                }}
              </Dropzone>
Benny answered 6/5, 2019 at 23:55 Comment(2)
Have you tried anything so far? What happens if you simply omit the attribute?Lagniappe
@ChrisG - it returns an empty array (completed ˃ []), as in nothing got uploaded.Benny
A
3

You can just use like with regular input, so you can do multiple file types like: image/*,.pdf.

Reference here.

Armidaarmiger answered 7/5, 2019 at 0:5 Comment(3)
I'm sorry, @codecubed.io, but I don't quite know what you mean by "just use like with regular input," do you mean instead of accept="image/*, i could have input="image/*, *.pdf, *.doc*..." etc.?Benny
It doesn't work for all platforms, as they say in their documentation. You can use "video/*, image/png", but ".pdf, image/*" won't let PDF documents to be accepted. Instead for pdf you need "application/pdf"Bloodshed
Reffer to the solutionBloodshed
U
2

This code works for me:

accept: {
    'image/jpeg': ['.jpeg', '.png'],
    'application/pdf': ['.pdf']
}
Unoccupied answered 12/12, 2023 at 6:22 Comment(2)
Please add some explanation to your answer such that others can learn from it. As far as I see, this won't allow the upload of Word documents or videosFoetid
It helped in my case. Thanks!Ledesma
T
1

I had this exact same issue.

react-dropzone uses attr-accept to handle accepting files. Let's look at the source code for the latter.

* @param file {File} https://developer.mozilla.org/en-US/docs/Web/API/File
 * @param acceptedFiles {string}
 * @returns {boolean}

...

export default function(file, acceptedFiles) {
  if (file && acceptedFiles) {
    ...
  }
  return true
}

To get a return value of true, simply input a falsy string value, i.e. ''

Tonietonight answered 25/6, 2019 at 20:46 Comment(0)
T
1

Just remove accept prop from <Dropzone /> and it will allow any file type.

Tungstate answered 13/5, 2020 at 7:34 Comment(0)
H
0

If you use useDropZone, then it will be like this

const {inputProps,...rest }=useDropZone({
onDrop,//onDrop function
acceptFiles:'image/png' //<--- here you provide input related info
})
Hatter answered 23/9, 2020 at 15:23 Comment(1)
It doesn't work for all platforms, as they say in their documentation. You can use "video/*, image/png", but ".pdf, image/*" won't let PDF documents to be accepted.Bloodshed

© 2022 - 2024 — McMap. All rights reserved.