|
import React, { useState } from 'react'; |
|
import { Button } from "./ui/button"; |
|
import { Input } from "./ui/input"; |
|
|
|
|
|
const Upload = ({ token, validate }) => { |
|
console.log('token********', token); |
|
const [file, setFile] = useState(null); |
|
const [uploading, setUploading] = useState(false); |
|
const [uploadProgress, setUploadProgress] = useState(0); |
|
|
|
const handleFileChange = (event) => { |
|
const file = event.target.files?.[0]; |
|
|
|
if (file) { |
|
setFile(file); |
|
} |
|
}; |
|
|
|
const handleUpload = async () => { |
|
if (!file) { |
|
return; |
|
} |
|
|
|
setUploading(true); |
|
setUploadProgress(0); |
|
|
|
try { |
|
const xhr = new XMLHttpRequest(); |
|
const formData = new FormData(); |
|
formData.append('file', file); |
|
|
|
xhr.upload.onprogress = (event) => { |
|
if (event.lengthComputable) { |
|
const percentComplete = (event.loaded / event.total) * 100; |
|
setUploadProgress(Math.round(percentComplete)); |
|
} |
|
}; |
|
|
|
xhr.onload = async () => { |
|
if (xhr.status === 200) { |
|
const response = JSON.parse(xhr.responseText); |
|
console.log('File uploaded successfully:', response); |
|
} else { |
|
console.error('Error uploading file:', xhr.statusText); |
|
} |
|
setUploading(false); |
|
}; |
|
|
|
xhr.onerror = () => { |
|
console.error('Error uploading file'); |
|
setUploading(false); |
|
}; |
|
|
|
xhr.open('POST', '/upload'); |
|
xhr.setRequestHeader('Authorization', `Bearer ${token}`); |
|
xhr.setRequestHeader('Accept', 'application/json'); |
|
xhr.send(formData); |
|
validate(); |
|
} catch (error) { |
|
console.error('Error uploading file:', error); |
|
setUploading(false); |
|
} |
|
}; |
|
|
|
return ( |
|
<div className="flex items-center space-x-2"> |
|
<input type="file" onChange={handleFileChange} style={{display: file ? 'none' : 'block'}} /> |
|
<button className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 disabled:bg-gray-400" onClick={handleUpload} disabled={uploading} style={{display: file ? 'block' : 'none'}}> |
|
{uploading ? `Uploading... ${uploadProgress}%` : `Upload ${file?.name}`} |
|
</button> |
|
{uploading && ( |
|
<div className="w-full bg-gray-200 rounded-full h-2.5 dark:bg-gray-700 mt-2"> |
|
<div className="bg-blue-600 h-2.5 rounded-full" style={{ width: `${uploadProgress}%` }}></div> |
|
</div> |
|
)} |
|
</div> |
|
); |
|
}; |
|
|
|
export default Upload; |