how to upload images to api using drop zone and get back images from api and delete the images from api

i have created a file using drop zone in it now I want to post images to Api using drop zone and get that images from api and also delete the image from Api I am sharing my code

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>"use client";
import React, { useCallback, useMemo, useState, useEffect } from "react";
import { parse } from "cookie";
import { Vortex } from "react-loader-spinner";
import axios from "axios";
import { baseURL } from "@/utils/constants";
import { CiImageOn } from "react-icons/ci";
import { VscClose } from "react-icons/vsc";
import { useDropzone } from "react-dropzone";
import { useMediaQuery } from "react-responsive";
import { MdOutlineCloudUpload } from "react-icons/md";
import { FaFolder } from "react-icons/fa6";
import { MdDeleteOutline } from "react-icons/md";
const baseStyle = {
display: "flex",
flexDirection: "column",
justifyContent: "center",
alignItems: "center",
padding: "15px",
borderWidth: 1,
borderStyle: "dashed",
borderRadius: 2,
borderColor: "#b2bec3",
backgroundColor: "#ffff",
color: "#bdbdbd",
transition: "border .3s ease-in-out",
height: "180px",
width: "100%",
};
const activeStyle = {
borderColor: "#2196f3",
};
const acceptStyle = {
borderColor: "#00e676",
};
const rejectStyle = {
borderColor: "#ff1744",
};
export default function UploadImages({ workorderid }) {
const [files, setFiles] = useState([]);
useEffect(() => {
getAllImages();
}, []);
const getAllImages = async () => {
if (!workorderid) {
return;
}
const doc_cookie = parse(document?.cookie);
const response = await axios.get(`${baseURL}/v1/workorder_images`, {
headers: {
Authorization: doc_cookie?.access_token,
"Content-Type": "application/json",
},
params: {
workorder_id: workorderid,
},
});
if (response?.status === 200) {
setFiles(response?.data);
console.log(response)
}
};
const handleDeleteImages = async (id) => {
if (!workorderid) {
return;
}
const doc_cookie = parse(document?.cookie);
const response = await axios.delete(`${baseURL}/v1/workorder_images`, {
headers: {
Authorization: doc_cookie?.access_token,
"Content-Type": "application/json",
},
params: {
workorder_id: workorderid,
image_id: id,
},
});
if (response?.status === 200) {
}
};
const onDrop = useCallback((acceptedFiles) => {
const newFiles = acceptedFiles.map((file) =>
Object.assign(file, {
preview: URL.createObjectURL(file),
})
);
setFiles((prevFiles) => [...prevFiles, ...newFiles]);
newFiles.forEach(file => uploadFile(file));
}, []);
const uploadFile = async (file) => {
if (!workorderid) {
return;
}
const formData = new FormData();
formData.append("workorder_id", workorderid);
formData.append("image_file", file);
const doc_cookie = parse(document?.cookie);
try {
const response = await axios.post(`${baseURL}/v1/workorder_images`, formData, {
headers: {
Authorization: doc_cookie?.access_token,
"Content-Type": "multipart/form-data",
},
});
console.log(response.data);
connsole.log("File uploaded successfully!");
} catch (error) {
console.error("Error uploading file:", error);
} finally {
}
};
const {
getRootProps,
getInputProps,
isDragActive,
isDragAccept,
isDragReject,
} = useDropzone({
onDrop,
accept: "image/jpeg, image/png, image/jpg, image/gif, image/webp",
multiple: true,
});
const style = useMemo(
() => ({
...baseStyle,
...(isDragActive ? activeStyle : {}),
...(isDragAccept ? acceptStyle : {}),
...(isDragReject ? rejectStyle : {}),
}),
[isDragActive, isDragReject, isDragAccept]
);
const thumbs = files.map((file) => (
<div
key={file.name}
className="h-[150px] border border-slate-200 relative "
>
<img src={file.preview} alt={file.name} className="h-[150px] w-full " />
<div className="w-full box-border py-1 px-1 flex justify-end border-b border-slate-200 absolute -bottom-[2px] ">
<button
className="border w-8 h-8 flex gap-1 items-center border-red-500 justify-center bg-red-500
text-white rounded-md tracking-wide"
>
<MdDeleteOutline onClick={() => handleDeleteImages(file.id)} className="text-xl" />
</button>
</div>
</div>
));
useEffect(
() => () => {
files.forEach((file) => URL.revokeObjectURL(file.preview));
},
[files]
);
const handleCloseModal = () => {
document.getElementById("upload-images").close();
};
return (
<div>
<button
onClick={() => document.getElementById("upload-images").showModal()}
className="flex px-2 py-2 hover:bg-slate-200 rounded-md text-slate-700 text-sm w-full text-left items-center"
>
<CiImageOn className="font-medium text-base mr-2" />
Upload Images
</button>
<dialog id="upload-images" className="modal">
<div className="modal-box max-w-screen-md w-full px-1 py-2 sm:px-4 sm:py-4">
<div className="flex justify-between items-center">
<h2 className="text-xl capitalize"> Upload Images</h2>
<VscClose
onClick={handleCloseModal}
className="text-2xl hover:cursor-pointer hover:bg-red-600 hover:rounded hover:text-white"
/>
</div>
<section className=" w-full mt-3 ">
<div {...getRootProps({ style })}>
<input {...getInputProps()} />
<div className="w-full text-center">
<FaFolder className="text-4xl text-[#6767fe] mx-auto mb-1" />
<p className="text-base font-bold tracking-wide text-slate-600">
Drag your images and videos here to start uploading
</p>
<div className="flex justify-center items-center my-1 gap-[5px]">
<hr className="h-[2px] w-14 bg-slate-300" />
<p>OR</p>
<hr className="h-[2px] w-14 bg-slate-300" />
</div>
<button className="flex items-center font-bold gap-1 mx-auto mt-1 text-white text-sm tracking-wide bg-[#6767fe] py-1 px-2 rounded">
Browse files <MdOutlineCloudUpload className="text-xl" />
</button>
</div>
</div>
<aside className="w-full grid xl:grid-cols-4 lg:grid-cols-3 mt-3 md:grid-cols-2 grid-cols-1 gap-4 ">
{thumbs}
</aside>
</section>
<div className="modal-action">
</div>
</div>
</dialog>
</div>
);
}
</code>
<code>"use client"; import React, { useCallback, useMemo, useState, useEffect } from "react"; import { parse } from "cookie"; import { Vortex } from "react-loader-spinner"; import axios from "axios"; import { baseURL } from "@/utils/constants"; import { CiImageOn } from "react-icons/ci"; import { VscClose } from "react-icons/vsc"; import { useDropzone } from "react-dropzone"; import { useMediaQuery } from "react-responsive"; import { MdOutlineCloudUpload } from "react-icons/md"; import { FaFolder } from "react-icons/fa6"; import { MdDeleteOutline } from "react-icons/md"; const baseStyle = { display: "flex", flexDirection: "column", justifyContent: "center", alignItems: "center", padding: "15px", borderWidth: 1, borderStyle: "dashed", borderRadius: 2, borderColor: "#b2bec3", backgroundColor: "#ffff", color: "#bdbdbd", transition: "border .3s ease-in-out", height: "180px", width: "100%", }; const activeStyle = { borderColor: "#2196f3", }; const acceptStyle = { borderColor: "#00e676", }; const rejectStyle = { borderColor: "#ff1744", }; export default function UploadImages({ workorderid }) { const [files, setFiles] = useState([]); useEffect(() => { getAllImages(); }, []); const getAllImages = async () => { if (!workorderid) { return; } const doc_cookie = parse(document?.cookie); const response = await axios.get(`${baseURL}/v1/workorder_images`, { headers: { Authorization: doc_cookie?.access_token, "Content-Type": "application/json", }, params: { workorder_id: workorderid, }, }); if (response?.status === 200) { setFiles(response?.data); console.log(response) } }; const handleDeleteImages = async (id) => { if (!workorderid) { return; } const doc_cookie = parse(document?.cookie); const response = await axios.delete(`${baseURL}/v1/workorder_images`, { headers: { Authorization: doc_cookie?.access_token, "Content-Type": "application/json", }, params: { workorder_id: workorderid, image_id: id, }, }); if (response?.status === 200) { } }; const onDrop = useCallback((acceptedFiles) => { const newFiles = acceptedFiles.map((file) => Object.assign(file, { preview: URL.createObjectURL(file), }) ); setFiles((prevFiles) => [...prevFiles, ...newFiles]); newFiles.forEach(file => uploadFile(file)); }, []); const uploadFile = async (file) => { if (!workorderid) { return; } const formData = new FormData(); formData.append("workorder_id", workorderid); formData.append("image_file", file); const doc_cookie = parse(document?.cookie); try { const response = await axios.post(`${baseURL}/v1/workorder_images`, formData, { headers: { Authorization: doc_cookie?.access_token, "Content-Type": "multipart/form-data", }, }); console.log(response.data); connsole.log("File uploaded successfully!"); } catch (error) { console.error("Error uploading file:", error); } finally { } }; const { getRootProps, getInputProps, isDragActive, isDragAccept, isDragReject, } = useDropzone({ onDrop, accept: "image/jpeg, image/png, image/jpg, image/gif, image/webp", multiple: true, }); const style = useMemo( () => ({ ...baseStyle, ...(isDragActive ? activeStyle : {}), ...(isDragAccept ? acceptStyle : {}), ...(isDragReject ? rejectStyle : {}), }), [isDragActive, isDragReject, isDragAccept] ); const thumbs = files.map((file) => ( <div key={file.name} className="h-[150px] border border-slate-200 relative " > <img src={file.preview} alt={file.name} className="h-[150px] w-full " /> <div className="w-full box-border py-1 px-1 flex justify-end border-b border-slate-200 absolute -bottom-[2px] "> <button className="border w-8 h-8 flex gap-1 items-center border-red-500 justify-center bg-red-500 text-white rounded-md tracking-wide" > <MdDeleteOutline onClick={() => handleDeleteImages(file.id)} className="text-xl" /> </button> </div> </div> )); useEffect( () => () => { files.forEach((file) => URL.revokeObjectURL(file.preview)); }, [files] ); const handleCloseModal = () => { document.getElementById("upload-images").close(); }; return ( <div> <button onClick={() => document.getElementById("upload-images").showModal()} className="flex px-2 py-2 hover:bg-slate-200 rounded-md text-slate-700 text-sm w-full text-left items-center" > <CiImageOn className="font-medium text-base mr-2" /> Upload Images </button> <dialog id="upload-images" className="modal"> <div className="modal-box max-w-screen-md w-full px-1 py-2 sm:px-4 sm:py-4"> <div className="flex justify-between items-center"> <h2 className="text-xl capitalize"> Upload Images</h2> <VscClose onClick={handleCloseModal} className="text-2xl hover:cursor-pointer hover:bg-red-600 hover:rounded hover:text-white" /> </div> <section className=" w-full mt-3 "> <div {...getRootProps({ style })}> <input {...getInputProps()} /> <div className="w-full text-center"> <FaFolder className="text-4xl text-[#6767fe] mx-auto mb-1" /> <p className="text-base font-bold tracking-wide text-slate-600"> Drag your images and videos here to start uploading </p> <div className="flex justify-center items-center my-1 gap-[5px]"> <hr className="h-[2px] w-14 bg-slate-300" /> <p>OR</p> <hr className="h-[2px] w-14 bg-slate-300" /> </div> <button className="flex items-center font-bold gap-1 mx-auto mt-1 text-white text-sm tracking-wide bg-[#6767fe] py-1 px-2 rounded"> Browse files <MdOutlineCloudUpload className="text-xl" /> </button> </div> </div> <aside className="w-full grid xl:grid-cols-4 lg:grid-cols-3 mt-3 md:grid-cols-2 grid-cols-1 gap-4 "> {thumbs} </aside> </section> <div className="modal-action"> </div> </div> </dialog> </div> ); } </code>
"use client";
import React, { useCallback, useMemo, useState, useEffect } from "react";
import { parse } from "cookie";
import { Vortex } from "react-loader-spinner";
import axios from "axios";
import { baseURL } from "@/utils/constants";
import { CiImageOn } from "react-icons/ci";
import { VscClose } from "react-icons/vsc";
import { useDropzone } from "react-dropzone";
import { useMediaQuery } from "react-responsive";
import { MdOutlineCloudUpload } from "react-icons/md";
import { FaFolder } from "react-icons/fa6";
import { MdDeleteOutline } from "react-icons/md";

const baseStyle = {
  display: "flex",
  flexDirection: "column",
  justifyContent: "center",
  alignItems: "center",
  padding: "15px",
  borderWidth: 1,
  borderStyle: "dashed",
  borderRadius: 2,
  borderColor: "#b2bec3",
  backgroundColor: "#ffff",
  color: "#bdbdbd",
  transition: "border .3s ease-in-out",
  height: "180px",
  width: "100%",
};

const activeStyle = {
  borderColor: "#2196f3",
};

const acceptStyle = {
  borderColor: "#00e676",
};

const rejectStyle = {
  borderColor: "#ff1744",
};

export default function UploadImages({ workorderid }) {
  const [files, setFiles] = useState([]);

useEffect(() => {
  getAllImages();
}, []);
 
const getAllImages = async () => {
  if (!workorderid) {
    return;
  }
  const doc_cookie = parse(document?.cookie);

  const response = await axios.get(`${baseURL}/v1/workorder_images`, {
    headers: {
      Authorization: doc_cookie?.access_token,
      "Content-Type": "application/json",
    },
    params: {
      workorder_id: workorderid,
    },
  });
  if (response?.status === 200) {
    setFiles(response?.data);
    console.log(response)
  }
};

 const handleDeleteImages = async (id) => {
    if (!workorderid) {
      return;
    }
    const doc_cookie = parse(document?.cookie);
    const response = await axios.delete(`${baseURL}/v1/workorder_images`, {
      headers: {
        Authorization: doc_cookie?.access_token,
        "Content-Type": "application/json",
      },
      params: {
        workorder_id: workorderid,
        image_id: id,
      },
    });
    if (response?.status === 200) {
      
    }
  };

  const onDrop = useCallback((acceptedFiles) => {
    const newFiles = acceptedFiles.map((file) =>
      Object.assign(file, {
        preview: URL.createObjectURL(file),
      })
    );

    setFiles((prevFiles) => [...prevFiles, ...newFiles]);

    
    newFiles.forEach(file => uploadFile(file));
  }, []);

  const uploadFile = async (file) => {
    if (!workorderid) {
      return;
    }

    

    const formData = new FormData();
    formData.append("workorder_id", workorderid);
    formData.append("image_file", file);
 
    const doc_cookie = parse(document?.cookie);

    try {
      const response = await axios.post(`${baseURL}/v1/workorder_images`, formData, {
        headers: {
          Authorization: doc_cookie?.access_token,
          "Content-Type": "multipart/form-data",
        },
      });

      console.log(response.data);
      connsole.log("File uploaded successfully!");
    } catch (error) {
     
     console.error("Error uploading file:", error);
    } finally {
      
    }
  };



  const {
    getRootProps,
    getInputProps,
    isDragActive,
    isDragAccept,
    isDragReject,
  } = useDropzone({
    onDrop,
    accept: "image/jpeg, image/png, image/jpg, image/gif, image/webp",
    multiple: true,
  });

  const style = useMemo(
    () => ({
      ...baseStyle,
      ...(isDragActive ? activeStyle : {}),
      ...(isDragAccept ? acceptStyle : {}),
      ...(isDragReject ? rejectStyle : {}),
    }),
    [isDragActive, isDragReject, isDragAccept]
  );

  const thumbs = files.map((file) => (
    <div
      key={file.name}
      className="h-[150px]   border border-slate-200 relative "
    >
      <img src={file.preview} alt={file.name} className="h-[150px] w-full " />
      <div className="w-full  box-border py-1 px-1 flex justify-end border-b border-slate-200   absolute -bottom-[2px]   ">
        <button
          className="border w-8 h-8 flex gap-1 items-center  border-red-500    justify-center  bg-red-500
        text-white rounded-md tracking-wide"
        >
          <MdDeleteOutline onClick={() => handleDeleteImages(file.id)}  className="text-xl" />
        </button>
      </div>
    </div>
  ));

  useEffect(
    () => () => {
      files.forEach((file) => URL.revokeObjectURL(file.preview));
    },
    [files]
  );

  const handleCloseModal = () => {
    document.getElementById("upload-images").close();
  };

  return (
    <div>
      <button
        onClick={() => document.getElementById("upload-images").showModal()}
        className="flex px-2 py-2 hover:bg-slate-200 rounded-md  text-slate-700 text-sm w-full text-left items-center"
      >
        <CiImageOn className="font-medium text-base mr-2" />
        Upload Images
      </button>
      <dialog id="upload-images" className="modal">
        <div className="modal-box  max-w-screen-md w-full px-1 py-2 sm:px-4 sm:py-4">
          <div className="flex justify-between items-center">
            <h2 className="text-xl capitalize"> Upload Images</h2>
            <VscClose
              onClick={handleCloseModal}
              className="text-2xl hover:cursor-pointer hover:bg-red-600 hover:rounded hover:text-white"
            />
          </div>

          <section className=" w-full mt-3  ">
            <div {...getRootProps({ style })}>
              <input {...getInputProps()} />
              <div className="w-full text-center">
                <FaFolder className="text-4xl text-[#6767fe] mx-auto mb-1" />
                <p className="text-base font-bold tracking-wide text-slate-600">
                  Drag your images and videos here to start uploading
                </p>
                <div className="flex justify-center items-center my-1 gap-[5px]">
                  <hr className="h-[2px] w-14 bg-slate-300" />
                  <p>OR</p>
                  <hr className="h-[2px] w-14 bg-slate-300" />
                </div>
                <button className="flex items-center font-bold gap-1 mx-auto mt-1 text-white text-sm tracking-wide bg-[#6767fe] py-1 px-2 rounded">
                  Browse files <MdOutlineCloudUpload className="text-xl" />
                </button>
              </div>
            </div>
            <aside className="w-full grid xl:grid-cols-4 lg:grid-cols-3 mt-3 md:grid-cols-2 grid-cols-1  gap-4 ">
              {thumbs}
            </aside>
          </section>

      
          <div className="modal-action">
            
        
          </div>
        </div>
      </dialog>
    </div>
  );
}

here i create a function upload image will be used for uploading images to Api and getallimages function will be used for fetching all images from Api and handledeleteimages will be used for delete images from Api.
now check the code my code is correct or not
i want to post images, get images and delete images from Api

New contributor

Muhammad Adil is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật