uploadForm.tsx 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. "use client";
  2. import { useState } from "react";
  3. interface FileData {
  4. id: string;
  5. filename: string;
  6. mimetype: string;
  7. size: number;
  8. createdAt: string;
  9. updatedAt: string;
  10. }
  11. export const UploadForm = ({ onFileUploaded }: { onFileUploaded?: (file: FileData) => void }) => {
  12. const [isUploading, setIsUploading] = useState(false);
  13. const handleFileUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
  14. if (e.target.files && e.target.files[0]) {
  15. setIsUploading(true);
  16. const file = e.target.files[0];
  17. const formData = new FormData();
  18. formData.append("file", file);
  19. try {
  20. const response = await fetch("/api/upload", {
  21. method: "POST",
  22. body: formData,
  23. });
  24. const result = await response.json();
  25. if (result.success) {
  26. // Call the callback to add the new file to the table
  27. if (onFileUploaded) {
  28. onFileUploaded(result.file);
  29. }
  30. // Reset the file input
  31. e.target.value = '';
  32. } else {
  33. alert(`Upload failed: ${result.error || 'Unknown error'}`);
  34. }
  35. } catch (error) {
  36. console.error("Upload error:", error);
  37. alert("Failed to upload file");
  38. } finally {
  39. setIsUploading(false);
  40. }
  41. }
  42. };
  43. return (
  44. <div>
  45. <input
  46. type="file"
  47. name="file"
  48. onChange={handleFileUpload}
  49. disabled={isUploading}
  50. className="block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100"
  51. />
  52. {isUploading && (
  53. <div className="mt-2 text-sm text-gray-600">Uploading...</div>
  54. )}
  55. </div>
  56. );
  57. };