upload images in MERN stack

Viewed 16

I want to save the images into the database uploaded from the React.js but it is not getting uploaded. It works fine in the postman but not in the React.js.

In the database I am saving only the file's path not the full data [Array] of the file.

The state:let [preview_image, setPreview_Image] = useState("")

The file handler function:

const uploadFileHandler = async (e) => {
    const file = e.target.files[0];   //Here it logs the file's data
    let formData = new FormData();
    let image = formData.append("preview_image", file); //image logs the undefined
    setUploading(true);

    try {
      const config = {
        headers: {
          "Content-Type": "multipart/form-data",
          "x-access-token": adminInfo.data.JWToken,
        },
      };
      const { data } = await axios.post(
        "http://localhost:8000/v1/template/create",
        formData,
        config
      );
      setPreview_Image(data);
      setUploading(false);
    } catch (error) {
      setUploading(false);
    }
  };

The file uploader:

<Form.Group controlId="preview_image">
    <Form.Label>Image</Form.Label>
    <Form.Control
      type="text"
      placeholder="Upload Image url"
      value={preview_image}
      onChange={(e) => setPreview_Image(e.target.value)}
    ></Form.Control>
     <Form.Control
      type="file"
      label="Choose file"
      onChange={uploadFileHandler}
     ></Form.Control>
  </Form.Group>

The error: enter image description here

Not sure why I am getting the error.

0 Answers
Related