import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core'; import { HwobsProvider } from '../lib/hwobs.service'; import { CommonModule } from '@angular/common'; @Component({ selector: 'upload-file', templateUrl: './upload-file.component.html', styleUrls: ['./upload-file.component.scss'], standalone: true, imports: [CommonModule], // 在 imports 中添加 CommonModule }) export class UploadFileComponent implements OnInit { @Input() url: string = ""; @Output() onUrlChange: EventEmitter = new EventEmitter() uploader: HwobsProvider | undefined; isUploading: boolean = false; // 控制“正在上传”提示的变量 constructor() { } ngOnInit() { this.uploader = new HwobsProvider({ bucketName: "nova-cloud", prefix: "dev/jxnu/storage/", host: "https://app.fmode.cn/", access_key_id: "XSUWJSVMZNHLWFAINRZ1", secret_access_key: "P4TyfwfDovVNqz08tI1IXoLWXyEOSTKJRVlsGcV6" }); } file: File | undefined; fileData: any = ""; fileList: File[] = []; async upload() { if (!this.file) { alert("请先选择文件!"); return; } this.isUploading = true; // 显示“正在上传”提示 let filename = this.file.name; let dateStr = `${new Date().getFullYear()}${new Date().getMonth() + 1}${new Date().getDate()}`; let hourStr = `${new Date().getHours()}${new Date().getMinutes() + 1}${new Date().getSeconds()}`; let key = `${dateStr}/${hourStr}-${filename}`; try { // 上传文件 let attachment = await this.uploader?.uploadFile(this.file, key); console.log(attachment); // 获取文件 URL this.url = attachment?.get("url") || ""; // 通过 EventEmitter 传递 URL this.onUrlChange.emit(this.url); } catch (error) { console.error("上传失败:", error); alert("上传失败,请重试!"); } finally { this.isUploading = false; // 隐藏“正在上传”提示 } } /** * 文件选择器 选择文件触发事件 * @param event */ async onFileChange(event: any) { console.log(event); // 将选择的文件列表赋值给 fileList this.fileList = event?.target?.files; // 默认将第一个文件设置为展示区域文件 this.setFile(event?.target?.files?.[0]); } /** * 设置展示区域文件 * @param file */ async setFile(file: any) { this.file = file; // 将文件设置为展示区域文件 } /** * 判断是否为图片 */ isImage(url: string): boolean { return url.endsWith('.png') || url.endsWith('.jpg') || url.endsWith('.jpeg') || url.endsWith('.gif'); } /** * 判断是否为视频 */ isVideo(url: string): boolean { return url.endsWith('.mp4') || url.endsWith('.mov') || url.endsWith('.avi'); } }