uploadForm.tsx 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. const formData = new FormData();
  20. formData.append("file", file);
  21. try {
  22. const response = await fetch("/api/upload", {
  23. method: "POST",
  24. body: formData,
  25. });
  26. const result = await response.json();
  27. if (result.success) {
  28. // Invalidate the files query to trigger a refresh
  29. await queryClient.invalidateQueries({ queryKey: ["files"] });
  30. // Call the callback if provided
  31. if (onFileUploaded) {
  32. onFileUploaded(result.file);
  33. }
  34. // Reset the file input
  35. e.target.value = '';
  36. } else {
  37. alert(`Upload failed: ${result.error || 'Unknown error'}`);
  38. }
  39. } catch (error) {
  40. console.error("Upload error:", error);
  41. alert("Failed to upload file");
  42. } finally {
  43. setIsUploading(false);
  44. }
  45. }
  46. };
  47. return (
  48. <div>
  49. <input
  50. type="file"
  51. name="file"
  52. onChange={handleFileUpload}
  53. disabled={isUploading}
  54. 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"
  55. />
  56. {isUploading && (
  57. <div className="mt-2 text-sm text-gray-600">Uploading...</div>
  58. )}
  59. </div>
  60. );
  61. };