| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263 |
- "use client";
- import { useState } from "react";
- import { useQueryClient } from "@tanstack/react-query";
- interface FileData {
- id: string;
- filename: string;
- mimetype: string;
- size: number;
- createdAt: string;
- updatedAt: string;
- }
- export const UploadForm = ({ onFileUploaded }: { onFileUploaded?: (file: FileData) => void }) => {
- const [isUploading, setIsUploading] = useState(false);
- const queryClient = useQueryClient();
- const handleFileUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
- if (e.target.files && e.target.files[0]) {
- setIsUploading(true);
- const file = e.target.files[0];
- try {
- // Import the server action
- const { uploadFile } = await import('../actions/file-upload');
- const uploadedFile = await uploadFile(file);
- // Invalidate the files query to trigger a refresh
- await queryClient.invalidateQueries({ queryKey: ["files"] });
- // Call the callback if provided
- if (onFileUploaded) {
- onFileUploaded(uploadedFile);
- }
- // Reset the file input
- e.target.value = '';
- } catch (error) {
- console.error("Upload error:", error);
- alert("Failed to upload file");
- } finally {
- setIsUploading(false);
- }
- }
- };
- return (
- <div>
- <input
- type="file"
- name="file"
- onChange={handleFileUpload}
- disabled={isUploading}
- 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"
- />
- {isUploading && (
- <div className="mt-2 text-sm text-gray-600">Uploading...</div>
- )}
- </div>
- );
- };
|