| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566 |
- "use client";
- import { useState } from "react";
- 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 handleFileUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
- if (e.target.files && e.target.files[0]) {
- setIsUploading(true);
- const file = e.target.files[0];
- const formData = new FormData();
- formData.append("file", file);
- try {
- const response = await fetch("/api/upload", {
- method: "POST",
- body: formData,
- });
- const result = await response.json();
-
- if (result.success) {
- // Call the callback to add the new file to the table
- if (onFileUploaded) {
- onFileUploaded(result.file);
- }
-
- // Reset the file input
- e.target.value = '';
- } else {
- alert(`Upload failed: ${result.error || 'Unknown error'}`);
- }
- } 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>
- );
- };
|