import React, { useState, useEffect, useCallback } from 'react'; import axiosInstance from '../src/axiosSecure'; // Adjust the import path as needed import { CircularProgress } from '@mui/material'; // Import MUI CircularProgress for loading indicator const FileUploadWithPreview = ({ name, value, prefix, onUpload, label }) => { // Function to transform the original image URL to its corresponding thumbnail URL function transformToThumbnailUrl(originalUrl) { if (!originalUrl) return null; if (originalUrl.includes("thumb")) return originalUrl; // If the URL already contains 'thumb', return it as-is const parts = originalUrl.split('/'); parts.splice(parts.length - 1, 0, 'thumb'); // Insert 'thumb' before the filename return parts.join('/'); } // State for the thumbnail URL const [thumbnail, setThumbnail] = useState(value ? transformToThumbnailUrl(value) : null); const [isDragging, setIsDragging] = useState(false); const [isUploading, setIsUploading] = useState(false); // New state for tracking upload status useEffect(() => { setThumbnail(value ? transformToThumbnailUrl(value) : null); }, [value]); const handleDragEnter = useCallback((e) => { e.preventDefault(); e.stopPropagation(); setIsDragging(true); }, []); const handleDragLeave = useCallback((e) => { e.preventDefault(); e.stopPropagation(); setIsDragging(false); }, []); const handleDragOver = useCallback((e) => { e.preventDefault(); e.stopPropagation(); }, []); const handleDrop = useCallback((e) => { e.preventDefault(); e.stopPropagation(); setIsDragging(false); const { files: droppedFiles } = e.dataTransfer; processFile(droppedFiles[0]); // Process only the first dropped file }, []); const processFile = async (file) => { if (!file) return; setIsUploading(true); // Start uploading const formData = new FormData(); formData.append('image', file); formData.append('prefix', prefix); setThumbnail("/"); try { const response = await axiosInstance.post('upload', formData); const uploadedFile = response.data[0]; // Update state with the new thumbnail URL setThumbnail(uploadedFile.thumbUrl); // Invoke callback if provided if (onUpload) { onUpload(name, uploadedFile.originalUrl); } } catch (error) { console.error('Error uploading image:', error); } finally { setIsUploading(false); // End uploading } }; const handleFilesChange = (e) => { processFile(e.target.files[0]); // Process only the first selected file }; return (
Поставете сникма тук, или изберете файл с бутона
> )}