How to remove a file with React FilePond?

162 Views Asked by At

I'm working on a file upload component for images in my app, and I'm using react FilePond library for that.

for the upload I build an api and use it in the component bellow and it's working fine. the upload api endpoint returns the filepath in the server like https://<domaine.come>/image.png. and then I update my state (property.gallery) with this path.

upload

The problem

Now the issue is when I try to delete a file from the component. so I build a delete api endpoint for that that takes the filepath in the body of the request and returns a message if the image was deleted.


DELETE /api/attachements HTTP/1.1
Host: <server.com>
Content-Type: application/json
Content-Length: 205

{
    "filePath": "https://<domaine.come>/image.png"
}

So I want to know how i can Implement this remove feature in order to do this actions after clicking the (X) button on the image:

  • Call the delete api to remove the image from the server
  • Update the gallery by removing the deleted image

I tried the remove or the revert options but the documentations about that are not so clear for me. I lost I lot of time to implement this.

For the delete API use this: ${process.env.NEXT_PUBLIC_API_BASE_URL}${API_ENDPOINTS.DELETE_FILE}

This is the component I'm working on:

import { FilePond, registerPlugin } from "react-filepond";
import "filepond/dist/filepond.min.css";
import FilePondPluginImagePreview from "filepond-plugin-image-preview";
import "filepond-plugin-image-preview/dist/filepond-plugin-image-preview.css";
import FilePondPluginFilePoster from "filepond-plugin-file-poster";
import "filepond-plugin-file-poster/dist/filepond-plugin-file-poster.css";
import { useState } from "react";
import usePropertyListingStore from "@/store/zustand/usePropertyListingStore";

registerPlugin(FilePondPluginImagePreview, FilePondPluginFilePoster);

export default function MultipleFileUpload({ name }) {
  const [files, setFiles] = useState([]);
  // property.gallery contains the images that are already uploaded
  const { property, updatePropertyData } = usePropertyListingStore();

  console.log(property.gallery);

  const handleGalleryLoad = (filePath) => {
    updatePropertyData({ gallery: [...property.gallery, filePath] });
  };

  const handleGalleryInit = () => {
    if (property.gallery) {
      const gallery = property.gallery.map((image) => {
        return {
          source: image,
          options: {
            type: "local",
            metadata: {
              poster: image,
            },
          },
        };
      });

      setFiles(gallery);
    }
  };

  return (
    <FilePond
      name={name}
      files={files}
      className="multiple"
      required={true}
      onupdatefiles={setFiles}
      allowMultiple={true}
      maxFiles={6}
      server={{
        timeout: 7000,
        process: {
          url: `${process.env.NEXT_PUBLIC_API_BASE_URL}${API_ENDPOINTS.UPLOAD_IMAGE}`,
          method: "POST",
          onload: (filePath) => {
            handleGalleryLoad(filePath);
          },
        },
      }}
      oninit={() => handleGalleryInit()}
    />
  );
}


Waiting for your remarks and answers and thank you so much in advance :)

1

There are 1 best solutions below

1
On

You can do this by utilising the allowRemove and onremovefile props. When the remove button is clicked, you need to perform two actions: call the delete API to remove the image from the server and update the gallery by removing the deleted image. You can do this in the onremovefile callback function. Something like this should work,

import { FilePond, registerPlugin } from "react-filepond";
//...rest of your imports...

registerPlugin(FilePondPluginImagePreview, FilePondPluginFilePoster);

export default function MultipleFileUpload({ name }) {
  //... rest of yourcomponent code...

  const handleRemoveFile = (removedFile) => {
    // Call the delete API to remove the image from the server
    const filePath = removedFile.source;
    fetch(`${process.env.NEXT_PUBLIC_API_BASE_URL}${API_ENDPOINTS.DELETE_FILE}`, {
      method: "DELETE",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ filePath }),
    })
      .then((response) => response.json())
      .then((data) => {
        // Check if the delete API was successful
        if (data.message === "Image deleted successfully") {
          // Update the gallery by removing the deleted image
          updatePropertyData({
            gallery: property.gallery.filter((image) => image !== filePath),
          });
        }
      })
      .catch((error) => {
        // handle error here...
      });
  };

  return (
    <FilePond
      ...
      allowRemove={true} // Allow removing files
      onremovefile={handleRemoveFile} // Callback for file removal
      ...
    />
  );
}