dapidmini
dapidmini

Reputation: 1625

how to send file to server with react dropzone uploader in react js

I want to use react-dropzone-uploader to choose image file and then upload it to my php server (codeigniter 4, if it matters). but even though I already defined xhr in the parameters, it gives an error xhr is undefined. why is that?

here's my code: codesandbox

import React from "react";
import "react-dropzone-uploader/dist/styles.css";
import Dropzone from "react-dropzone-uploader";
import "./styles.css";

export default function App() {
  const toast = (innerHTML) => {
    const el = document.getElementById("toast");
    el.innerHTML = innerHTML;
    el.className = "show";
    setTimeout(() => {
      el.className = el.className.replace("show", "");
    }, 3000);
  };

  const handleChangeStatus = ({ meta, file, xhr }, status) => {
    console.log("handlechangestatus", status, meta, file);
    if (status === "done") {
      console.log('xhr', xhr);
      let response = JSON.parse(xhr.response);
    }
  };

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <React.Fragment>
        <div id="toast">Upload</div>
        <Dropzone
          // getUploadParams={getUploadParams}
          onChangeStatus={handleChangeStatus}
          maxFiles={1}
          multiple={false}
          canCancel={false}
          inputContent="Drop A File"
          styles={{
            dropzone: { height: 200 },
            dropzoneActive: { borderColor: "green" }
          }}
        />
      </React.Fragment>
    </div>
  );
}

Upvotes: 0

Views: 2285

Answers (1)

Saurabh Shelar
Saurabh Shelar

Reputation: 28

First of all, handleChangeStatus wouldn't accept XHR param. It only accepts meta & file.

You would need to set getUploadParams.

  const getUploadParams = ({ meta }) => {
    return { url: "https://httpbin.org/post" };
  };

<Dropzone
          // getUploadParams={getUploadParams}
          onChangeStatus={handleChangeStatus}
          getUploadParams={getUploadParams}
          maxFiles={1}
          multiple={false}
          canCancel={false}
          inputContent="Drop A File"
          styles={{
            dropzone: { height: 200 },
            dropzoneActive: { borderColor: "green" }
          }}
        />

Try to read the documentation. You'll get it.

Additional Links: https://react-dropzone-uploader.js.org/docs/quick-start#dropzone https://react-dropzone-uploader.js.org/docs/api#onsubmit

Upvotes: 1

Related Questions