upload-file.component.ts 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
  2. import { HwobsProvider } from '../lib/hwobs.service';
  3. import { CommonModule } from '@angular/common';
  4. @Component({
  5. selector: 'upload-file',
  6. templateUrl: './upload-file.component.html',
  7. styleUrls: ['./upload-file.component.scss'],
  8. standalone: true,
  9. imports: [CommonModule], // 在 imports 中添加 CommonModule
  10. })
  11. export class UploadFileComponent implements OnInit {
  12. @Input() url: string = "";
  13. @Output() onUrlChange: EventEmitter<string> = new EventEmitter<string>()
  14. uploader: HwobsProvider | undefined;
  15. isUploading: boolean = false; // 控制“正在上传”提示的变量
  16. constructor() { }
  17. ngOnInit() {
  18. this.uploader = new HwobsProvider({
  19. bucketName: "nova-cloud",
  20. prefix: "dev/jxnu/storage/",
  21. host: "https://app.fmode.cn/",
  22. access_key_id: "XSUWJSVMZNHLWFAINRZ1",
  23. secret_access_key: "P4TyfwfDovVNqz08tI1IXoLWXyEOSTKJRVlsGcV6"
  24. });
  25. }
  26. file: File | undefined;
  27. fileData: any = "";
  28. fileList: File[] = [];
  29. async upload() {
  30. if (!this.file) {
  31. alert("请先选择文件!");
  32. return;
  33. }
  34. this.isUploading = true; // 显示“正在上传”提示
  35. let filename = this.file.name;
  36. let dateStr = `${new Date().getFullYear()}${new Date().getMonth() + 1}${new Date().getDate()}`;
  37. let hourStr = `${new Date().getHours()}${new Date().getMinutes() + 1}${new Date().getSeconds()}`;
  38. let key = `${dateStr}/${hourStr}-${filename}`;
  39. try {
  40. // 上传文件
  41. let attachment = await this.uploader?.uploadFile(this.file, key);
  42. console.log(attachment);
  43. // 获取文件 URL
  44. this.url = attachment?.get("url") || "";
  45. // 通过 EventEmitter 传递 URL
  46. this.onUrlChange.emit(this.url);
  47. } catch (error) {
  48. console.error("上传失败:", error);
  49. alert("上传失败,请重试!");
  50. } finally {
  51. this.isUploading = false; // 隐藏“正在上传”提示
  52. }
  53. }
  54. /**
  55. * 文件选择器 选择文件触发事件
  56. * @param event
  57. */
  58. async onFileChange(event: any) {
  59. console.log(event);
  60. // 将选择的文件列表赋值给 fileList
  61. this.fileList = event?.target?.files;
  62. // 默认将第一个文件设置为展示区域文件
  63. this.setFile(event?.target?.files?.[0]);
  64. }
  65. /**
  66. * 设置展示区域文件
  67. * @param file
  68. */
  69. async setFile(file: any) {
  70. this.file = file; // 将文件设置为展示区域文件
  71. }
  72. /**
  73. * 判断是否为图片
  74. */
  75. isImage(url: string): boolean {
  76. return url.endsWith('.png') || url.endsWith('.jpg') || url.endsWith('.jpeg') || url.endsWith('.gif');
  77. }
  78. /**
  79. * 判断是否为视频
  80. */
  81. isVideo(url: string): boolean {
  82. return url.endsWith('.mp4') || url.endsWith('.mov') || url.endsWith('.avi');
  83. }
  84. }