import React, { useState } from "react"; import { Input, Button, Card, Space, Typography, Divider } from "antd"; import { SendOutlined } from "@ant-design/icons"; import ChatFileUpload from "./index"; const { TextArea } = Input; const { Text } = Typography; interface ChatMessage { id: string; type: "text" | "file"; content: string; timestamp: Date; fileInfo?: { url: string; name: string; type: string; size: number; }; } const ChatFileUploadExample: React.FC = () => { const [messages, setMessages] = useState([]); const [inputValue, setInputValue] = useState(""); // 处理文件上传 const handleFileUploaded = (fileInfo: { url: string; name: string; type: string; size: number; }) => { const newMessage: ChatMessage = { id: Date.now().toString(), type: "file", content: `文件: ${fileInfo.name}`, timestamp: new Date(), fileInfo, }; setMessages(prev => [...prev, newMessage]); }; // 处理文本发送 const handleSendText = () => { if (!inputValue.trim()) return; const newMessage: ChatMessage = { id: Date.now().toString(), type: "text", content: inputValue, timestamp: new Date(), }; setMessages(prev => [...prev, newMessage]); setInputValue(""); }; // 格式化文件大小 const formatFileSize = (bytes: number) => { if (bytes === 0) return "0 B"; const k = 1024; const sizes = ["B", "KB", "MB", "GB"]; const i = Math.floor(Math.log(bytes) / Math.log(k)); return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i]; }; // 获取文件类型图标 const getFileTypeIcon = (type: string, name: string) => { const lowerType = type.toLowerCase(); const lowerName = name.toLowerCase(); if (lowerType.startsWith("image/")) { return "🖼️"; } else if (lowerType.startsWith("video/")) { return "🎥"; } else if (lowerType.startsWith("audio/")) { return "🎵"; } else if (lowerType === "application/pdf") { return "📄"; } else if (lowerName.endsWith(".doc") || lowerName.endsWith(".docx")) { return "📝"; } else if (lowerName.endsWith(".xls") || lowerName.endsWith(".xlsx")) { return "📊"; } else if (lowerName.endsWith(".ppt") || lowerName.endsWith(".pptx")) { return "📈"; } else { return "📎"; } }; return (
功能特点:
  • 点击文件按钮直接唤醒文件选择框
  • 选择文件后自动上传
  • 上传成功后自动发送到聊天框
  • 支持各种文件类型和大小限制
  • 显示文件图标和大小信息
{/* 聊天消息区域 */} {messages.length === 0 ? (
暂无消息,开始聊天吧!
) : (
{messages.map(message => (
{message.type === "text" ? (
{message.content}
) : (
{getFileTypeIcon( message.fileInfo!.type, message.fileInfo!.name, )} {message.fileInfo!.name}
大小: {formatFileSize(message.fileInfo!.size)}
类型: {message.fileInfo!.type}
查看文件
)}
{message.timestamp.toLocaleTimeString()}
))}
)}
{/* 输入区域 */}