1

I have a problem with sending files in React. So, I have a big form. All data send, but files send empty object, not binary files. I use Formik and Dropzone.

Result

enter image description here

Some part of Formik and request. Jsondata is that some of the values need to change json format and fileData is my files.

      <Formik
          initialValues={{
            name: "",
            ...
            file: null,
            note: "",
          }}
          // validationSchema={validationSchema}
          onSubmit={async (values) => {
            const jsonData = {
              ...values,
              address: JSON.stringify(values.address),
              products: JSON.stringify(values.products),
            };
            console.log(values.file[0]);

            let fileData = new FormData();
            fileData.append("file", values.file[0]);

            await axios.post("https://nehra.az/api/add-supplier", { jsonData, fileData });
          }}

Parent component

   <div className="form-input">
                  <Dropzone setFieldValue={setFieldValue} />
                  <span className="error-span">
                    <ErrorMessage name="file" />
                  </span>{" "}
                </div>

Child component (Dropzone)

  const { getRootProps, getInputProps, isFocused, isDragAccept, isDragReject, acceptedFiles } = useDropzone({
    onDrop: (acceptedFiles) => props.setFieldValue("file", acceptedFiles),
  });

  const files = acceptedFiles.map((file) => <li key={file.path}>{file.path}</li>);

  return (
    <div className="container">
      <div {...getRootProps({ style })}>
        <input {...getInputProps()} multiple />
        <p> Click to download the file or drag the file here.</p>
        {files ?? <ul>{files}</ul>}{" "}
      </div>
    </div>
  );

Rahil Əliyev
  • 247
  • 2
  • 8

0 Answers0