1
yyb
2026-04-29 aec5cbead319feabb2e44ddd5bf99a0af01ca506
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
<template>
  <view class="album-image-upload">
    <view class="actions" v-if="!readonly">
      <u-button
        type="primary"
        size="small"
        :loading="uploading"
        :disabled="uploading || innerList.length >= limit"
        @click="chooseFromAlbum"
      >
        {{ buttonText }}
      </u-button>
      <view class="tip" v-if="tipText">{{ tipText }}</view>
    </view>
 
    <view v-if="innerList.length" class="list">
      <view
        v-for="(img, idx) in innerList"
        :key="img.id || img.url || idx"
        class="item"
      >
        <image
          class="img"
          :src="img.previewUrl || img.url"
          mode="aspectFill"
          @click="preview(idx)"
        />
        <view v-if="!readonly" class="del" @click.stop="remove(idx)">×</view>
      </view>
    </view>
 
    <!-- 隐藏画布:用于图片加水印 -->
    <canvas
      v-if="enableWatermark"
      :canvas-id="canvasId"
      :id="canvasId"
      :style="{
        position: 'absolute',
        left: '-9999px',
        top: '-9999px',
        width: canvasWidth + 'px',
        height: canvasHeight + 'px'
      }"
      :width="canvasWidth"
      :height="canvasHeight"
    />
  </view>
</template>
 
<script setup>
import { computed, getCurrentInstance, ref, watch } from "vue";
import config from "@/config.js";
import { getToken } from "@/utils/auth";
import { normalizeFileUrl } from "@/utils/filePreview";
 
const props = defineProps({
  modelValue: { type: Array, default: () => [] },
  // 最大张数
  limit: { type: Number, default: 6 },
  // 上传接口 path(会拼接 config.baseUrl)
  action: { type: String, default: "/invoiceLedger/upload" },
  // 上传字段名
  name: { type: String, default: "file" },
  // 仅相册(固定),暴露出来方便未来扩展
  sourceType: { type: Array, default: () => ["album"] },
  // 选择压缩/原图
  sizeType: { type: Array, default: () => ["compressed", "original"] },
  // 文案
  buttonText: { type: String, default: "从相册选择" },
  tipText: { type: String, default: "仅支持从相册选择" },
  // 只读
  readonly: { type: Boolean, default: false },
 
  // 水印
  enableWatermark: { type: Boolean, default: true },
  watermarkText: { type: [String, Function], default: "" },
 
  // 上传前业务校验/拦截:返回 false 直接拦截
  beforeUpload: { type: Function, default: null },
});
 
const emit = defineEmits(["update:modelValue", "change", "error"]);
 
const instance = getCurrentInstance();
const uploading = ref(false);
const innerList = ref([]);
 
watch(
  () => props.modelValue,
  val => {
    innerList.value = Array.isArray(val) ? val.filter(v => v?.url) : [];
  },
  { immediate: true, deep: true }
);
 
const canvasId = `album_wm_canvas_${Date.now()}_${Math.random()
  .toString(16)
  .slice(2)}`;
const canvasWidth = ref(1);
const canvasHeight = ref(1);
 
const uploadUrl = computed(() => {
  const base = config.baseUrl || "";
  return base + props.action;
});
 
const resolveWatermarkText = () => {
  try {
    return typeof props.watermarkText === "function"
      ? props.watermarkText()
      : props.watermarkText;
  } catch (e) {
    return "";
  }
};
 
const normalizeUploadResultToFile = data => {
  if (!data) return null;
  if (Array.isArray(data)) return normalizeUploadResultToFile(data[0]);
  if (typeof data === "string") {
    const url = normalizeFileUrl(data);
    return url ? { url, downloadUrl: url } : null;
  }
  if (typeof data === "object") {
    const url = normalizeFileUrl(
      data.url || data.downloadUrl || data.tempPath || data.path
    );
    if (url) return { ...data, url, downloadUrl: url };
    return null;
  }
  return null;
};
 
const getAdaptiveWatermarkStyle = (width, height) => {
  const w = Math.max(1, Number(width) || 1);
  const h = Math.max(1, Number(height) || 1);
  const shortSide = Math.min(w, h);
  const longSide = Math.max(w, h);
  // 分段适配:小图减小字号,大图保持当前视觉效果
  const isSmallImage = shortSide <= 720;
  const fontSize = isSmallImage
    ? Math.max(
        10,
        Math.min(28, Math.floor(shortSide * 0.016 + longSide * 0.004))
      )
    : Math.max(
        14,
        Math.min(56, Math.floor(shortSide * 0.022 + longSide * 0.006))
      );
  return {
    fontSize,
    padding: Math.max(isSmallImage ? 4 : 5, Math.floor(fontSize * 0.4)),
    lineGap: Math.max(isSmallImage ? 1 : 2, Math.floor(fontSize * 0.16)),
    edgeGap: 0,
  };
};
 
const addWatermarkByBrowserCanvas = (tempFilePath, text) => {
  return new Promise((resolve, reject) => {
    try {
      const wmText = String(text || "").trim();
      if (!wmText) return resolve(tempFilePath);
 
      const img = new Image();
      img.onload = () => {
        try {
          const w = img.naturalWidth || img.width || 1;
          const h = img.naturalHeight || img.height || 1;
          const canvas = document.createElement("canvas");
          canvas.width = w;
          canvas.height = h;
          const ctx = canvas.getContext("2d");
          if (!ctx) return resolve(tempFilePath);
 
          ctx.drawImage(img, 0, 0, w, h);
 
          const lines = wmText.split(/\r?\n/).filter(Boolean);
          const { fontSize, padding, lineGap, edgeGap } =
            getAdaptiveWatermarkStyle(w, h);
 
          ctx.font = `${fontSize}px sans-serif`;
          const maxChars = Math.max(...lines.map(t => (t || "").length), 0);
          const approxTextWidth = Math.min(
            w * 0.55,
            Math.max(fontSize * maxChars * 0.5, fontSize * 4)
          );
          const blockW = approxTextWidth + padding * 2;
          const blockH =
            lines.length * fontSize + (lines.length - 1) * lineGap + padding * 2;
          const blockX = Math.max(0, w - blockW - edgeGap);
          const blockY = Math.max(0, h - blockH - edgeGap);
 
          ctx.fillStyle = "rgba(0,0,0,0.2)";
          ctx.fillRect(blockX, blockY, blockW, blockH);
          ctx.fillStyle = "rgba(255,255,255,0.95)";
          lines.forEach((t, idx) => {
            const textWidth = ctx.measureText(t).width;
            const x = Math.max(blockX + padding, blockX + blockW - padding - textWidth);
            const y = blockY + padding + fontSize + idx * (fontSize + lineGap);
            ctx.fillText(t, x, y);
          });
 
          canvas.toBlob(
            blob => {
              if (!blob) return resolve(tempFilePath);
              resolve(URL.createObjectURL(blob));
            },
            "image/jpeg",
            0.92
          );
        } catch (e) {
          resolve(tempFilePath);
        }
      };
      img.onerror = () => resolve(tempFilePath);
      img.src = tempFilePath;
    } catch (e) {
      reject(e);
    }
  });
};
 
const addWatermarkToImage = (tempFilePath, text) => {
  return new Promise((resolve, reject) => {
    if (!tempFilePath) return reject(new Error("图片路径不存在"));
    const wmText = String(text || "").trim();
    if (!props.enableWatermark || !wmText) return resolve(tempFilePath);
    // H5 端优先使用浏览器原生 canvas,避免 uni canvas 生成空白图
    if (typeof window !== "undefined" && typeof document !== "undefined") {
      addWatermarkByBrowserCanvas(tempFilePath, wmText)
        .then(resolve)
        .catch(() => resolve(tempFilePath));
      return;
    }
 
    uni.getImageInfo({
      src: tempFilePath,
      success: info => {
        try {
          const w = info.width || 1;
          const h = info.height || 1;
          canvasWidth.value = w;
          canvasHeight.value = h;
 
          const ctx = uni.createCanvasContext(canvasId, instance);
          ctx.drawImage(tempFilePath, 0, 0, w, h);
 
          const lines = wmText.split(/\r?\n/).filter(Boolean);
          const { fontSize, padding, lineGap, edgeGap } =
            getAdaptiveWatermarkStyle(w, h);
 
          ctx.setFontSize(fontSize);
          ctx.setFillStyle("rgba(0,0,0,0.2)");
 
          const maxChars = Math.max(...lines.map(t => (t || "").length), 0);
          const approxTextWidth = Math.min(
            w * 0.55,
            Math.max(fontSize * maxChars * 0.5, fontSize * 4)
          );
          const blockW = approxTextWidth + padding * 2;
          const blockH =
            lines.length * fontSize + (lines.length - 1) * lineGap + padding * 2;
          const blockX = Math.max(0, w - blockW - edgeGap);
          const blockY = Math.max(0, h - blockH - edgeGap);
 
          ctx.fillRect(blockX, blockY, blockW, blockH);
          ctx.setFillStyle("rgba(255,255,255,0.95)");
          lines.forEach((t, idx) => {
            const textWidth = fontSize * String(t || "").length * 0.55;
            const x = Math.max(blockX + padding, blockX + blockW - padding - textWidth);
            const y = blockY + padding + fontSize + idx * (fontSize + lineGap);
            ctx.fillText(t, x, y);
          });
 
          ctx.draw(false, () => {
            uni.canvasToTempFilePath(
              {
                canvasId,
                width: w,
                height: h,
                destWidth: w,
                destHeight: h,
                fileType: "jpg",
                quality: 0.92,
                success: r => resolve(r.tempFilePath),
                fail: err => reject(err),
              },
              instance
            );
          });
        } catch (e) {
          reject(e);
        }
      },
      fail: err => reject(err),
    });
  });
};
 
const uploadOneByH5FormData = (filePath, extraFormData = {}) => {
  return new Promise(async (resolve, reject) => {
    try {
      const resp = await fetch(filePath);
      const blob = await resp.blob();
      const formData = new FormData();
      const explicitName = String(
        extraFormData?.fileName || extraFormData?.originalName || ""
      ).trim();
      const pathExt = getFileExtFromPath(filePath);
      const mimeExt = String(blob?.type || "")
        .toLowerCase()
        .split("/")
        .pop();
      const uploadFileName =
        explicitName || `file_${Date.now()}.${pathExt || mimeExt || "jpg"}`;
      formData.append(props.name, blob, uploadFileName);
 
      Object.keys(extraFormData || {}).forEach(key => {
        if (key === "fileName" || key === "originalName") return;
        const val = extraFormData[key];
        if (val === undefined || val === null) return;
        formData.append(key, String(val));
      });
 
      const xhr = new XMLHttpRequest();
      xhr.open("POST", uploadUrl.value, true);
      xhr.setRequestHeader("Authorization", "Bearer " + getToken());
      xhr.onload = () => {
        try {
          const body = JSON.parse(xhr.responseText || "{}");
          if (body.code === 200) {
            const file = normalizeUploadResultToFile(body.data);
            if (!file) return reject(new Error("上传成功但未返回文件信息"));
            resolve(file);
          } else {
            reject(new Error(body.msg || "上传失败"));
          }
        } catch (e) {
          reject(e);
        }
      };
      xhr.onerror = () => reject(new Error("上传失败"));
      xhr.send(formData);
    } catch (e) {
      reject(e);
    }
  });
};
 
const uploadOne = (filePath, extraFormData = {}) => {
  const isH5BlobPath =
    typeof window !== "undefined" &&
    typeof FormData !== "undefined" &&
    String(filePath || "").startsWith("blob:");
  if (isH5BlobPath) {
    return uploadOneByH5FormData(filePath, extraFormData);
  }
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: uploadUrl.value,
      filePath,
      name: props.name,
      formData: extraFormData,
      header: { Authorization: "Bearer " + getToken() },
      success: res => {
        try {
          const body = JSON.parse(res.data || "{}");
          if (body.code === 200) {
            const file = normalizeUploadResultToFile(body.data);
            if (!file) return reject(new Error("上传成功但未返回文件信息"));
            resolve(file);
          } else {
            reject(new Error(body.msg || "上传失败"));
          }
        } catch (e) {
          reject(e);
        }
      },
      fail: err => reject(err),
    });
  });
};
 
const getFileExtFromPath = filePath => {
  const raw = String(filePath || "").split("?")[0].split("#")[0];
  const match = raw.match(/\.([a-zA-Z0-9]+)$/);
  return (match?.[1] || "").toLowerCase();
};
 
const getFileNameFromPath = filePath => {
  const raw = String(filePath || "").split("?")[0].split("#")[0];
  const seg = raw.split("/").pop() || "";
  return seg.split("\\").pop() || "";
};
 
const buildUploadMeta = (originalPath, rawOriginalName = "") => {
  const cleanOriginalName = String(rawOriginalName || "").trim();
  const pathName = getFileNameFromPath(originalPath);
  const fallbackName = cleanOriginalName || pathName;
  const ext =
    getFileExtFromPath(fallbackName) || getFileExtFromPath(originalPath) || "jpg";
  const fileName = fallbackName || `${Date.now()}.${ext}`;
  return {
    ext,
    fileName,
    formData: { fileName },
  };
};
 
const resolvePreviewPath = (wmPath, originPath) => {
  return new Promise(resolve => {
    if (!wmPath) return resolve(originPath || "");
    uni.getImageInfo({
      src: wmPath,
      success: () => resolve(wmPath),
      fail: () => resolve(originPath || wmPath || ""),
    });
  });
};
 
const emitList = list => {
  emit("update:modelValue", list);
  emit("change", list);
};
 
const chooseFromAlbum = () => {
  if (props.readonly) return;
  if (typeof props.beforeUpload === "function") {
    const ok = props.beforeUpload();
    if (ok === false) return;
  }
 
  const remaining = Math.max(0, props.limit - innerList.value.length);
  if (remaining <= 0) {
    uni.showToast({ title: `最多只能上传${props.limit}张`, icon: "none" });
    return;
  }
 
  uni.chooseImage({
    count: remaining,
    sizeType: props.sizeType,
    sourceType: props.sourceType,
    success: async res => {
      const paths = res?.tempFilePaths || [];
      const tempFiles = Array.isArray(res?.tempFiles) ? res.tempFiles : [];
      if (!paths.length) return;
 
      uploading.value = true;
      uni.showLoading({ title: "正在上传...", mask: true });
      try {
        const wmText = resolveWatermarkText();
        for (let idx = 0; idx < paths.length; idx++) {
          const p = paths[idx];
          const picked = tempFiles[idx] || {};
          const originalName = picked.name || getFileNameFromPath(p);
          const wmPath = await addWatermarkToImage(p, wmText);
          const uploadMeta = buildUploadMeta(p, originalName);
          const uploaded = await uploadOne(wmPath, uploadMeta.formData);
          // 保留后端返回地址用于后续回显/提交,立即预览优先展示加水印后的本地图
          uploaded.previewUrl = await resolvePreviewPath(wmPath, p);
          uploaded.originalName = uploaded.originalName || uploadMeta.fileName;
          uploaded.suffix = uploaded.suffix || uploadMeta.ext;
          innerList.value.push(uploaded);
          emitList(innerList.value.slice());
        }
        uni.showToast({ title: "上传成功", icon: "none" });
      } catch (e) {
        emit("error", e);
        uni.showToast({ title: e?.message || "上传失败", icon: "none" });
      } finally {
        uploading.value = false;
        uni.hideLoading();
      }
    },
  });
};
 
const remove = idx => {
  const list = innerList.value.slice();
  list.splice(idx, 1);
  innerList.value = list;
  emitList(list);
};
 
const preview = idx => {
  const urls = innerList.value
    .map(i => i?.previewUrl || i?.url || i?.downloadUrl)
    .filter(Boolean);
  if (!urls.length) return;
  uni.previewImage({ urls, current: urls[idx] || urls[0] });
};
</script>
 
<style scoped lang="scss">
.album-image-upload {
  width: 100%;
}
 
.actions {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 6px 0;
}
 
.tip {
  font-size: 12px;
  color: #999;
}
 
.list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  padding: 8px 0 4px;
}
 
.item {
  position: relative;
  width: 76px;
  height: 76px;
  border-radius: 8px;
  overflow: hidden;
  background: #f5f5f5;
  border: 1px solid #eee;
}
 
.img {
  width: 100%;
  height: 100%;
}
 
.del {
  position: absolute;
  right: 4px;
  top: 4px;
  width: 18px;
  height: 18px;
  border-radius: 50%;
  background: rgba(0, 0, 0, 0.55);
  color: #fff;
  font-size: 14px;
  line-height: 18px;
  text-align: center;
}
</style>