Blame view

components/vendor/ImageUploadPopUp.js 6.09 KB
jaymehta committed
1
import { PlusOutlined } from "@ant-design/icons";
.  
jaymehta committed
2
import { Upload, message, Image } from "antd";
jaymehta committed
3 4 5 6
import axios from "axios";
import { getSession } from "next-auth/react";
import React, { useEffect, useState } from "react";
import { useSelector } from "react-redux";
.  
jaymehta committed
7
import { toast } from "react-toastify";
jaymehta committed
8
import { cleanImage } from "../../services/imageHandling";
.  
jaymehta committed
9 10 11 12 13 14 15
const getBase64 = file =>
  new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
jaymehta committed
16

.  
jaymehta committed
17
const ImageUploadPopUp = ({ isUpdate, setimagesArrayComponent, populatedImages, imagesArrayComponent }) => {
jaymehta committed
18 19
  //   const { loadedUser } = useSelector(state => state.loadedUser);
  const [session, setSession] = useState();
.  
jaymehta committed
20 21
  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewImage, setPreviewImage] = useState("");
.  
jaymehta committed
22 23
  const [fileList, setFileList] = useState([]);
  const [uploading, setUploading] = useState(false);
jaymehta committed
24 25 26 27 28 29 30 31 32 33 34
  console.log("populatedImages", populatedImages);
  const transformImageData = images => {
    return images.map((image, index) => ({
      uid: index,
      name: `image-${index}.jpg`, // You can adjust the name based on your requirements
      status: "done",
      url: image.url, // Assuming image.url is the URL of the image
      id: image.id,
      deleteId: image.deleteId
    }));
  };
.  
jaymehta committed
35

jaymehta committed
36 37 38 39 40 41 42
  useEffect(() => {
    const fetchSession = async () => {
      setSession(await getSession());
    };
    fetchSession();
    // dispatch(getLoggedInVendor());
  }, []);
jaymehta committed
43 44 45 46 47 48 49 50 51 52
  useEffect(() => {
    // console.log("populatedImages.id", populatedImages.id);
    if (!populatedImages) {
      return;
    }
    const initialImages = transformImageData([{ url: cleanImage(populatedImages.image.data?.attributes), deleteId: populatedImages.image.data?.id, id: populatedImages.id }]);
    if (populatedImages) {
      setFileList(initialImages);
    }
  }, [populatedImages]);
.  
jaymehta committed
53 54

  console.log("fileList", fileList);
.  
jaymehta committed
55
  // let formData = new FormData();
jaymehta committed
56
  let finalId;
jaymehta committed
57

.  
jaymehta committed
58 59 60 61 62 63 64
  const handlePreview = async file => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj);
    }
    setPreviewImage(file.url || file.preview);
    setPreviewOpen(true);
  };
jaymehta committed
65

.  
jaymehta committed
66 67
  const handleImageChange = async info => {
    console.log("info", info);
jaymehta committed
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
    const newFileList = [...info.fileList];

    if (info.file.status === "uploading") {
      setUploading(true);
      setFileList(newFileList);
      return;
    }

    if (info.file.status === "done") {
      let formData = new FormData();
      formData.append("files", info.file.originFileObj);

      try {
        const response = await axios.post(`${process.env.NEXT_PUBLIC_BACKEND_API_URL}/api/upload`, formData, {
          headers: {
            "Content-Type": "multipart/form-data",
            Authorization: `Bearer ${session.jwt}`
          }
        });

        if (response.status === 200) {
          const newFileId = response.data[0].id;

          // Update the file list with the new file ID
          const updatedFileList = newFileList.map(file => {
            if (file.uid === info.file.uid) {
              return {
                ...file,
                id: newFileId,
                url: response.data[0].url // You can add any other response data you need here
              };
            }
            return file;
          });

          setFileList(updatedFileList);
          setimagesArrayComponent([...imagesArrayComponent, newFileId]);
          message.success(`${info.file.name} uploaded successfully.`);
        }
      } catch (error) {
        message.error(`${info.file.name} upload failed.`);
      } finally {
        setUploading(false);
      }
    } else if (info.file.status === "removed") {
      // Handle file removal if needed
      const updatedFileList = newFileList.filter(file => file.uid !== info.file.uid);
      setFileList(updatedFileList);
    }
  };
  const handleCustomRequest = ({ file, onSuccess, onError }) => {
    setTimeout(() => {
      onSuccess({ id: finalId }, file);
    }, 2000);
  };
  const handleRemove = async file => {
jaymehta committed
124 125
    console.log("handle remove", file);
    const imageId = file.deleteId;
jaymehta committed
126 127 128 129
    if (!imageId) {
      message.error(`Failed to remove ${file.name}. Image ID not found.`);
      return;
    }
jaymehta committed
130 131
    setimagesArrayComponent(imagesArrayComponent.filter(item => item != imageId));
    setFileList([]);
jaymehta committed
132
    try {
jaymehta committed
133
      await axios.delete(`${process.env.NEXT_PUBLIC_BACKEND_API_URL}/api/upload/files/${imageId}`, {
jaymehta committed
134 135 136 137
        headers: {
          "Content-Type": "multipart/form-data",
          Authorization: `Bearer ${session.jwt}`
        }
jaymehta committed
138 139 140
      }); // Replace with your Strapi delete endpoint
      message.success(`${file.name} file removed successfully.`);
      setFileList(prevFileList => prevFileList.filter(item => item.uid !== file.uid));
jaymehta committed
141
    } catch (error) {
jaymehta committed
142
      message.error(`Failed to remove ${file.name}`);
jaymehta committed
143 144 145 146
    }
  };
  return (
    <div>
.  
jaymehta committed
147
      <Upload
jaymehta committed
148 149
        // customRequest={handleCustomRequest}
        // enterButton={true}
.  
jaymehta committed
150 151 152
        //  showUploadList={{ showRemoveIcon: false }}
        listType="picture-card"
        fileList={fileList}
jaymehta committed
153
        // multiple={false}
.  
jaymehta committed
154
        onChange={handleImageChange}
jaymehta committed
155
        onRemove={handleRemove}
.  
jaymehta committed
156 157 158
        onPreview={handlePreview}
      >
        {fileList?.length >= 1 ? null : (
jaymehta committed
159 160 161 162 163 164
          <div>
            <PlusOutlined />
            <div style={{ marginTop: 8 }}>Upload</div>
          </div>
        )}
      </Upload>
jaymehta committed
165
      {previewImage && (
.  
jaymehta committed
166 167 168 169 170 171 172 173 174 175 176 177
        <Image
          wrapperStyle={{
            display: "none"
            // zIndex: 23
          }}
          preview={{
            visible: previewOpen,
            onVisibleChange: visible => setPreviewOpen(visible),
            afterOpenChange: visible => !visible && setPreviewImage("")
          }}
          src={previewImage}
        />
jaymehta committed
178
      )}
.  
jaymehta committed
179
      {/* <button type="button" onClick={handleUpload} disabled={fileList ? fileList.length === 0 : true} loading={uploading} style={{ marginTop: 16 }}>
jaymehta committed
180
        {uploading ? "Uploading" : "Start Upload"}
.  
jaymehta committed
181
      </button> */}
jaymehta committed
182 183 184 185 186
    </div>
  );
};

export default ImageUploadPopUp;