ImageUploadPopUp.js 2.43 KB
import { PlusOutlined } from "@ant-design/icons";
import { Upload, message } from "antd";
import axios from "axios";
import { getSession } from "next-auth/react";
import React, { useEffect, useState } from "react";
import { useSelector } from "react-redux";

const ImageUploadPopUp = () => {
  //   const { loadedUser } = useSelector(state => state.loadedUser);
  const [session, setSession] = useState();
  useEffect(() => {
    const fetchSession = async () => {
      setSession(await getSession());
    };
    fetchSession();
    // dispatch(getLoggedInVendor());
  }, []);
  const [fileList, setFileList] = useState([]);
  const [uploading, setUploading] = useState(false);
  //   console.log("session", session);
  const handleUpload = async () => {
    const formData = new FormData();
    fileList.forEach(file => {
      console.log("file", file);
      formData.append("files", file);
    });
    console.log("fileList", fileList);
    console.log("formData", formData);

    setUploading(true);

    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}`
        }
      });
      console.log("response image", response);
      // eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MywiaWF0IjoxNzE2MzY5MzQyLCJleHAiOjE3MTg5NjEzNDJ9.dHTpIvuUi4r4Eh7n-74WKDXUlSaqvhjppGJ-1G4GvHk
      // if (response.status === 200) {
      //   message.success("upload successfully.");
      //   console.log("Uploaded file URL:", response.data[0].url); // The URL of the uploaded file
      // } else {
      //   message.error("upload failed.");
      // }
    } catch (error) {
      message.error("upload failed.");
    } finally {
      setUploading(false);
    }
  };

  const handleImageChange = info => {
    setFileList(info.fileList);
  };
  return (
    <div>
      <Upload listType="picture-card" fileList={fileList} beforeUpload={() => false} onChange={handleImageChange}>
        {fileList.length >= 8 ? null : (
          <div>
            <PlusOutlined />
            <div style={{ marginTop: 8 }}>Upload</div>
          </div>
        )}
      </Upload>
      <button type="button" onClick={handleUpload} disabled={fileList.length === 0} loading={uploading} style={{ marginTop: 16 }}>
        {uploading ? "Uploading" : "Start Upload"}
      </button>
    </div>
  );
};

export default ImageUploadPopUp;