Untitled

mail@pastecode.io avatar
unknown
plain_text
7 months ago
2.6 kB
2
Indexable
Never
import axios from 'axios';
import { useState } from 'react';

const FileUpload = () => {
    const [selectedFiles, setSelectedFiles] = useState({
        'mockpjteam1/image/general': [],
        'mockpjteam1/image/main': [],
        'mockpjteam1/image/sub': [],
    });

    const handleChange = (event) => {
		let folderPath = event.target.getAttribute('data-folder');
		setSelectedFiles(prevFiles => ({
			...prevFiles,
			[folderPath]: [...prevFiles[folderPath], event.target.files[0]],
		}));

		// Reset input field
		event.target.value = null;
	}

    const handleUpload = () => {
		Object.entries(selectedFiles).forEach(([folderPath, files]) => {
			files.forEach((file) => {
				if (file) {
					uploadFile(file, folderPath);
				}
			});
		});
}

    const uploadFile = async (file, folderPath) => {
       // Get the presigned URL from Laravel backend
       let response = await axios.post('(thay đổi cho phù hợp)/api/admin/seminar/create/presignUrl', {
           fileName: file.name,
           folderPath: folderPath
       });

       let presignedUrl = response.data.presignedUrl;

       // Now upload the file to S3 
       axios.put(presignedUrl, file, {
           headers: {
             'Content-Type': file.type,
           },
       })
       .then(res => {
           console.log('Upload success!');
           console.log('The public URL is:', response.data.publicUrl);
       })
       .catch(err => {
           console.error('Error uploading:', err);
       });
    }
	
	return (
        <div>
            <input 
                type="file"
                data-folder="mockpjteam1/image/General"
                onChange={handleChange}
            />
            <input 
                type="file"
                data-folder="mockpjteam1/image/Online"
                onChange={handleChange}
            />
            <input 
                type="file"
                data-folder="mockpjteam1/image/Sub"
                onChange={handleChange}
            />
            <button onClick={handleUpload}>Upload</button>
        </div>
    )
	
	
	
	// Giữ liệu sau khi đầy đủ nó sẽ kiểu như này
	/*
	'mockpjteam1/image/General': [
        FileObject1, // Gỡ bỏ "FileObjectx", thêm dữ liệu thực. Được tạo khi người dùng chọn tệp từ input.
        FileObject2,
        FileObject3,
        FileObject4
    ],
    'mockpjteam1/image/Online': [
        FileObject5, 
    ],
    'mockpjteam1/image/Sub': [
        FileObject6 
    ],
	*/