uploadForm.tsx 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. "use client";
  2. import { useState } from "react";
  3. import { useQueryClient } from "@tanstack/react-query";
  4. interface FileData {
  5. id: string;
  6. filename: string;
  7. mimetype: string;
  8. size: number;
  9. createdAt: string;
  10. updatedAt: string;
  11. }
  12. export const UploadForm = ({ onFileUploaded }: { onFileUploaded?: (file: FileData) => void }) => {
  13. const [isUploading, setIsUploading] = useState(false);
  14. const queryClient = useQueryClient();
  15. const handleFileUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
  16. if (e.target.files && e.target.files[0]) {
  17. setIsUploading(true);
  18. const file = e.target.files[0];
  19. try {
  20. // Import the server action
  21. const { uploadFile } = await import('../actions/file-upload');
  22. const uploadedFile = await uploadFile(file);
  23. // Invalidate the files query to trigger a refresh
  24. await queryClient.invalidateQueries({ queryKey: ["files"] });
  25. // Call the callback if provided
  26. if (onFileUploaded) {
  27. onFileUploaded(uploadedFile);
  28. }
  29. // Reset the file input
  30. e.target.value = '';
  31. } catch (error) {
  32. console.error("Upload error:", error);
  33. alert("Failed to upload file");
  34. } finally {
  35. setIsUploading(false);
  36. }
  37. }
  38. };
  39. return (
  40. <div>
  41. <input
  42. type="file"
  43. name="file"
  44. onChange={handleFileUpload}
  45. disabled={isUploading}
  46. 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"
  47. />
  48. {isUploading && (
  49. <div className="mt-2 text-sm text-gray-600">Uploading...</div>
  50. )}
  51. </div>
  52. );
  53. };