WXL
7 天以前 f806aff5702fc6be9c9348d51964366cbf434bf7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
<template>
  <el-dialog
    class="file-preview-dialog"
    :title="previewTitle"
    :visible.sync="previewVisible"
    width="80%"
    top="5vh"
    :close-on-click-modal="true"
    append-to-body
    @close="handleClose"
  >
    <!-- 加载状态 -->
    <div v-if="loading" class="preview-loading">
      <i
        class="el-icon-loading"
        style="font-size: 40px; margin-bottom: 16px;"
      ></i>
      <span>文件加载中...</span>
    </div>
 
    <!-- 图片预览 -->
    <div v-else-if="fileType === 'image'" class="preview-container">
      <div class="image-toolbar">
        <el-button-group>
          <el-button
            size="mini"
            @click="zoomImageIn"
            :disabled="imageScale >= 300"
          >
            <i class="el-icon-zoom-in"></i> 放大
          </el-button>
          <el-button size="mini" disabled>{{ imageScale }}%</el-button>
          <el-button
            size="mini"
            @click="zoomImageOut"
            :disabled="imageScale <= 50"
          >
            <i class="el-icon-zoom-out"></i> 缩小
          </el-button>
          <el-button size="mini" @click="resetImageZoom">
            <i class="el-icon-refresh-left"></i> 重置
          </el-button>
        </el-button-group>
 
        <el-button size="mini" type="success" @click="handleDownload">
          <i class="el-icon-download"></i> 下载
        </el-button>
      </div>
 
      <div class="image-viewport">
        <img
          :src="fileUrl"
          alt="预览图片"
          class="preview-image"
          :style="{ transform: `scale(${imageScale / 100})` }"
          @load="handleImageLoad"
        />
      </div>
    </div>
 
    <!-- PDF预览 -->
    <div v-else-if="fileType === 'pdf'" class="preview-container pdf-preview">
      <div class="pdf-toolbar">
        <el-button-group>
          <el-button
            size="mini"
            @click="changePage(currentPage - 1)"
            :disabled="currentPage <= 1"
          >
            <i class="el-icon-arrow-left"></i> 上一页
          </el-button>
          <el-button size="mini" disabled>
            第 {{ currentPage }} 页 / 共 {{ pageCount }} 页
          </el-button>
          <el-button
            size="mini"
            @click="changePage(currentPage + 1)"
            :disabled="currentPage >= pageCount"
          >
            <i class="el-icon-arrow-right"></i> 下一页
          </el-button>
        </el-button-group>
 
        <el-button-group class="zoom-controls">
          <el-button size="mini" @click="zoomOut" :disabled="scale <= 50">
            <i class="el-icon-zoom-out"></i> 缩小
          </el-button>
          <el-button size="mini" disabled> {{ scale }}% </el-button>
          <el-button size="mini" @click="zoomIn" :disabled="scale >= 200">
            <i class="el-icon-zoom-in"></i> 放大
          </el-button>
          <el-button size="mini" @click="resetZoom">
            <i class="el-icon-refresh-left"></i> 重置
          </el-button>
        </el-button-group>
 
        <el-button size="mini" type="success" @click="handleDownload">
          <i class="el-icon-download"></i> 下载
        </el-button>
      </div>
 
      <div class="pdf-content" v-loading="pdfLoading">
        <pdf
          ref="pdf"
          :src="pdfUrl"
          :page="currentPage"
          @num-pages="pageCount = $event"
          @page-loaded="currentPage = $event"
          @loaded="loadPdfHandler"
          @error="pdfErrorHandler"
          :style="{
            width: scale + '%',
            transform: 'scale(' + scale / 100 + ')',
            transformOrigin: '0 0'
          }"
        ></pdf>
      </div>
    </div>
 
    <!-- Office文档预览 -->
    <div
      v-else-if="fileType === 'office'"
      class="preview-container office-preview"
    >
      <div class="office-toolbar">
        <el-alert
          title="Office文档预览提示"
          description="建议下载后使用本地Office软件查看以获得最佳体验"
          type="info"
          show-icon
          :closable="false"
        />
        <el-button size="mini" type="success" @click="handleDownload">
          <i class="el-icon-download"></i> 下载文档
        </el-button>
      </div>
 
      <div class="office-content">
        <iframe
          :src="
            `https://view.officeapps.live.com/op/view.aspx?src=${encodeURIComponent(
              fileUrl
            )}`
          "
          width="100%"
          height="600px"
          frameborder="0"
        ></iframe>
      </div>
    </div>
 
    <!-- 不支持预览的文件类型 -->
    <div v-else class="preview-container unsupported-preview">
      <el-alert
        title="该文件格式不支持在线预览"
        :description="`文件类型: ${getFileExtension(fileName)}`"
        type="warning"
        show-icon
        :closable="false"
      />
 
      <div class="unsupported-actions">
        <el-button type="primary" @click="handleDownload">
          <i class="el-icon-download"></i> 下载文件
        </el-button>
        <el-button @click="handleClose">关闭</el-button>
      </div>
 
      <div class="file-info">
        <p><strong>文件名:</strong> {{ fileName }}</p>
        <p><strong>文件类型:</strong> {{ getFileExtension(fileName) }}</p>
      </div>
    </div>
  </el-dialog>
</template>
 
<script>
import pdf from "vue-pdf";
 
export default {
  name: "FilePreviewDialog",
  components: {
    pdf
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    file: {
      type: Object,
      default: () => ({})
    }
    // 添加baseUrlHt作为props传入
    // baseUrlHt: {
    //   type: String,
    //   default: process.env.VUE_APP_BASE_API
    // }
  },
  data() {
    return {
      // 预览控制
      previewVisible: this.visible,
      // 加载状态
      loading: false,
      pdfLoading: false,
      baseUrlHt: "",
      // 文件信息
      fileUrl: "",
      fileName: "",
      fileType: "",
      // PDF相关
      currentPage: 1,
      pageCount: 0,
      scale: 100,
      pageRotate: 0,
      // 图片相关
      imageScale: 100
    };
  },
  computed: {
    previewTitle() {
      return `文件预览 - ${this.fileName}`;
    },
    pdfUrl() {
      return this.fileUrl;
    }
  },
  watch: {
    visible(newVal) {
      this.previewVisible = newVal;
      if (newVal) {
        this.initPreview();
      }
    },
    previewVisible(newVal) {
      this.$emit("update:visible", newVal);
      if (!newVal) {
        this.handleClose();
      }
    }
  },
  created() {
    this.calculateBaseUrl();
  },
  methods: {
    /** URL处理函数 - 将完整URL替换为baseUrlHt */
    processFileUrl(url) {
      if (!url) return "";
 
      // 如果已经是完整的http或https链接
      if (url.startsWith("http://") || url.startsWith("https://")) {
        // 找到第三个斜杠后的位置,提取路径部分
        const thirdSlashIndex = url.indexOf("/", 8); // 从http://或https://之后开始找
        if (thirdSlashIndex !== -1) {
          return `${this.baseUrlHt}${url.substring(thirdSlashIndex)}`;
        }
        return this.baseUrlHt; // 如果没有路径部分,只返回baseUrlHt
      }
 
      // 相对路径处理
      if (url.startsWith("/")) {
        return `${this.baseUrlHt}${url}`;
      }
 
      return `${this.baseUrlHt}/${url}`;
    },
    /** 计算 baseUrlHt */
    calculateBaseUrl() {
      // 获取当前浏览器地址
      const currentUrl = window.location.href;
      console.log("当前浏览器地址:", currentUrl);
 
      try {
        // 使用 URL 对象解析
        const urlObj = new URL(currentUrl);
        // 获取主机名(IP 或域名)
        const hostname = urlObj.hostname;
        // 拼接端口 :9095
        this.baseUrlHt = `http://${hostname}:9095`;
        console.log("计算得到的 baseUrlHt:", this.baseUrlHt);
      } catch (error) {
        console.error("解析URL失败:", error);
        // 备用方案:使用正则提取
        const match = currentUrl.match(/https?:\/\/([^:\/]+)/);
        if (match) {
          this.baseUrlHt = `http://${match[1]}:9095`;
        } else {
          // 最后的备用方案
          this.baseUrlHt =
            process.env.VUE_APP_BASE_API || "http://localhost:9095";
        }
      }
    },
 
    /** 初始化预览 */
    initPreview() {
      if (!this.file) return;
 
      this.fileName = this.file.fileName || this.file.name || "未知文件";
      const originalUrl = this.file.fileUrl || this.file.path || this.file.url;
 
      // 处理URL,替换域名部分
      this.fileUrl = this.processFileUrl(originalUrl);
 
      this.fileType = this.getFileType(this.fileName);
 
      this.loading = true;
 
      // 重置状态
      this.currentPage = 1;
      this.scale = 100;
      this.imageScale = 100;
      this.pageCount = 0;
 
      // 模拟加载延迟
      setTimeout(() => {
        this.loading = false;
        if (this.fileType === "pdf") {
          this.pdfLoading = true;
        }
      }, 300);
    },
 
    /** 获取文件类型 */
    getFileType(fileName) {
      if (!fileName) return "other";
 
      const extension = fileName
        .split(".")
        .pop()
        .toLowerCase();
      const imageTypes = ["jpg", "jpeg", "png", "gif", "bmp", "webp"];
      const pdfTypes = ["pdf"];
      const officeTypes = ["doc", "docx", "xls", "xlsx", "ppt", "pptx"];
 
      if (imageTypes.includes(extension)) return "image";
      if (pdfTypes.includes(extension)) return "pdf";
      if (officeTypes.includes(extension)) return "office";
      return "other";
    },
 
    /** 获取文件扩展名 */
    getFileExtension(filename) {
      return (
        filename
          .split(".")
          .pop()
          .toLowerCase() || "未知"
      );
    },
 
    /** PDF加载完成 */
    loadPdfHandler() {
      this.pdfLoading = false;
      this.currentPage = 1;
    },
 
    /** PDF加载错误 */
    pdfErrorHandler(error) {
      console.error("PDF加载失败:", error);
      this.pdfLoading = false;
      this.$message.error("PDF文件加载失败,请尝试下载后查看");
      this.previewVisible = false;
    },
 
    /** 图片加载完成 */
    handleImageLoad() {
      this.loading = false;
    },
 
    /** 改变PDF页码 */
    changePage(newPage) {
      if (newPage < 1 || newPage > this.pageCount) return;
      this.currentPage = newPage;
    },
 
    /** PDF放大 */
    zoomIn() {
      if (this.scale >= 200) {
        this.$message.info("已放大到最大比例");
        return;
      }
      this.scale += 10;
    },
 
    /** PDF缩小 */
    zoomOut() {
      if (this.scale <= 50) {
        this.$message.info("已缩小到最小比例");
        return;
      }
      this.scale -= 10;
    },
 
    /** PDF重置缩放 */
    resetZoom() {
      this.scale = 100;
    },
 
    /** 图片放大 */
    zoomImageIn() {
      if (this.imageScale >= 300) {
        this.$message.info("已放大到最大比例");
        return;
      }
      this.imageScale += 20;
    },
 
    /** 图片缩小 */
    zoomImageOut() {
      if (this.imageScale <= 50) {
        this.$message.info("已缩小到最小比例");
        return;
      }
      this.imageScale -= 20;
    },
 
    /** 图片重置缩放 */
    resetImageZoom() {
      this.imageScale = 100;
    },
 
    /** 下载文件 - 也需要处理URL */
    handleDownload() {
      if (!this.fileUrl) {
        this.$message.warning("文件路径不存在,无法下载");
        return;
      }
 
      const link = document.createElement("a");
      link.href = this.fileUrl;
      link.download = this.fileName;
      link.style.display = "none";
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
 
      this.$message.success("开始下载文件");
    },
 
    /** 关闭对话框 */
    handleClose() {
      this.previewVisible = false;
      this.$emit("close");
 
      // 清理资源
      if (this.fileUrl && this.fileUrl.startsWith("blob:")) {
        URL.revokeObjectURL(this.fileUrl);
      }
    }
  }
};
</script>
 
<style scoped>
.file-preview-dialog {
  .preview-loading {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 400px;
    color: #909399;
  }
 
  .preview-container {
    display: flex;
    flex-direction: column;
    height: 70vh;
  }
 
  /* 工具栏通用样式 */
  .image-toolbar,
  .pdf-toolbar,
  .office-toolbar {
    padding: 15px 20px;
    background: #f5f7fa;
    border-bottom: 1px solid #ebeef5;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 10px;
  }
 
  /* 图片预览样式 */
  .image-viewport {
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    overflow: auto;
    padding: 20px;
    background: #f8f9fa;
  }
 
  .preview-image {
    max-width: 100%;
    max-height: 100%;
    transition: transform 0.3s ease;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  }
 
  /* PDF预览样式 */
  .pdf-content {
    flex: 1;
    overflow: auto;
    padding: 20px;
    background: #f8f9fa;
    display: flex;
    justify-content: center;
    align-items: flex-start;
  }
 
  /* Office预览样式 */
  .office-content {
    flex: 1;
    padding: 20px;
    background: #f8f9fa;
  }
 
  /* 不支持预览的样式 */
  .unsupported-preview {
    padding: 40px 20px;
    text-align: center;
  }
 
  .unsupported-actions {
    margin: 30px 0;
  }
 
  .unsupported-actions .el-button {
    margin: 0 10px;
  }
 
  .file-info {
    text-align: left;
    max-width: 400px;
    margin: 0 auto;
    padding: 20px;
    background: #f5f7fa;
    border-radius: 4px;
  }
 
  .file-info p {
    margin: 8px 0;
  }
}
 
/* 对话框样式调整 */
:deep(.el-dialog) {
  margin-top: 5vh !important;
}
 
:deep(.el-dialog__body) {
  padding: 0;
}
 
/* 响应式设计 */
@media (max-width: 768px) {
  .file-preview-dialog {
    :deep(.el-dialog) {
      width: 95% !important;
    }
 
    .preview-container {
      .image-toolbar,
      .pdf-toolbar,
      .office-toolbar {
        flex-direction: column;
        gap: 10px;
      }
    }
  }
}
</style>