feat: 添加文件上传功能,集成 S3 上传,优化上传进度显示和错误处理
This commit is contained in:
3
auto-imports.d.ts
vendored
3
auto-imports.d.ts
vendored
@@ -366,6 +366,9 @@ declare global {
|
||||
export type { HapticsOptions } from './src/composables/useVibrate'
|
||||
import('./src/composables/useVibrate')
|
||||
// @ts-ignore
|
||||
export type { UploadFetchOptions } from './src/utils/aws/s3'
|
||||
import('./src/utils/aws/s3')
|
||||
// @ts-ignore
|
||||
export type { PageInstance, InputInstance, ModalInstance, FormInstance, ContentInstance } from './src/utils/ionic-helper'
|
||||
import('./src/utils/ionic-helper')
|
||||
}
|
||||
|
||||
2
components.d.ts
vendored
2
components.d.ts
vendored
@@ -41,6 +41,7 @@ declare module 'vue' {
|
||||
IonModal: typeof import('@ionic/vue')['IonModal']
|
||||
IonNote: typeof import('@ionic/vue')['IonNote']
|
||||
IonPage: typeof import('@ionic/vue')['IonPage']
|
||||
IonProgressBar: typeof import('@ionic/vue')['IonProgressBar']
|
||||
IonRadio: typeof import('@ionic/vue')['IonRadio']
|
||||
IonRadioGroup: typeof import('@ionic/vue')['IonRadioGroup']
|
||||
IonRange: typeof import('@ionic/vue')['IonRange']
|
||||
@@ -99,6 +100,7 @@ declare global {
|
||||
const IonModal: typeof import('@ionic/vue')['IonModal']
|
||||
const IonNote: typeof import('@ionic/vue')['IonNote']
|
||||
const IonPage: typeof import('@ionic/vue')['IonPage']
|
||||
const IonProgressBar: typeof import('@ionic/vue')['IonProgressBar']
|
||||
const IonRadio: typeof import('@ionic/vue')['IonRadio']
|
||||
const IonRadioGroup: typeof import('@ionic/vue')['IonRadioGroup']
|
||||
const IonRange: typeof import('@ionic/vue')['IonRange']
|
||||
|
||||
@@ -34,7 +34,7 @@
|
||||
"@elysiajs/eden": "^1.4.5",
|
||||
"@ionic/vue": "^8.7.11",
|
||||
"@ionic/vue-router": "^8.7.11",
|
||||
"@riwa/api-types": "http://192.168.1.7:9527/api/riwa-eden-0.0.92.tgz",
|
||||
"@riwa/api-types": "http://192.168.1.7:9527/api/riwa-eden-0.0.100.tgz",
|
||||
"@tailwindcss/vite": "^4.1.18",
|
||||
"@vee-validate/yup": "^4.15.1",
|
||||
"@vueuse/core": "^14.1.0",
|
||||
|
||||
12
pnpm-lock.yaml
generated
12
pnpm-lock.yaml
generated
@@ -57,8 +57,8 @@ importers:
|
||||
specifier: ^8.7.11
|
||||
version: 8.7.11(@stencil/core@4.39.0)(vue-router@4.6.3(vue@3.5.25(typescript@5.9.3)))(vue@3.5.25(typescript@5.9.3))
|
||||
'@riwa/api-types':
|
||||
specifier: http://192.168.1.7:9527/api/riwa-eden-0.0.92.tgz
|
||||
version: '@riwa/eden@http://192.168.1.7:9527/api/riwa-eden-0.0.92.tgz(@elysiajs/eden@1.4.5(elysia@1.4.18(@sinclair/typebox@0.34.41)(exact-mirror@0.2.5(@sinclair/typebox@0.34.41))(file-type@21.1.1)(openapi-types@12.1.3)(typescript@5.9.3)))'
|
||||
specifier: http://192.168.1.7:9527/api/riwa-eden-0.0.100.tgz
|
||||
version: '@riwa/eden@http://192.168.1.7:9527/api/riwa-eden-0.0.100.tgz(@elysiajs/eden@1.4.5(elysia@1.4.18(@sinclair/typebox@0.34.41)(exact-mirror@0.2.5(@sinclair/typebox@0.34.41))(file-type@21.1.1)(openapi-types@12.1.3)(typescript@5.9.3)))'
|
||||
'@tailwindcss/vite':
|
||||
specifier: ^4.1.18
|
||||
version: 4.1.18(vite@7.2.7(@types/node@24.10.2)(jiti@2.6.1)(lightningcss@1.30.2)(terser@5.44.1)(yaml@2.8.2))
|
||||
@@ -2772,9 +2772,9 @@ packages:
|
||||
'@remirror/core-constants@3.0.0':
|
||||
resolution: {integrity: sha512-42aWfPrimMfDKDi4YegyS7x+/0tlzaqwPQCULLanv3DMIlu96KTJR0fM5isWX2UViOqlGnX6YFgqWepcX+XMNg==}
|
||||
|
||||
'@riwa/eden@http://192.168.1.7:9527/api/riwa-eden-0.0.92.tgz':
|
||||
resolution: {tarball: http://192.168.1.7:9527/api/riwa-eden-0.0.92.tgz}
|
||||
version: 0.0.92
|
||||
'@riwa/eden@http://192.168.1.7:9527/api/riwa-eden-0.0.100.tgz':
|
||||
resolution: {tarball: http://192.168.1.7:9527/api/riwa-eden-0.0.100.tgz}
|
||||
version: 0.0.100
|
||||
peerDependencies:
|
||||
'@elysiajs/eden': ^1.4.5
|
||||
|
||||
@@ -12099,7 +12099,7 @@ snapshots:
|
||||
|
||||
'@remirror/core-constants@3.0.0': {}
|
||||
|
||||
'@riwa/eden@http://192.168.1.7:9527/api/riwa-eden-0.0.92.tgz(@elysiajs/eden@1.4.5(elysia@1.4.18(@sinclair/typebox@0.34.41)(exact-mirror@0.2.5(@sinclair/typebox@0.34.41))(file-type@21.1.1)(openapi-types@12.1.3)(typescript@5.9.3)))':
|
||||
'@riwa/eden@http://192.168.1.7:9527/api/riwa-eden-0.0.100.tgz(@elysiajs/eden@1.4.5(elysia@1.4.18(@sinclair/typebox@0.34.41)(exact-mirror@0.2.5(@sinclair/typebox@0.34.41))(file-type@21.1.1)(openapi-types@12.1.3)(typescript@5.9.3)))':
|
||||
dependencies:
|
||||
'@elysiajs/eden': 1.4.5(elysia@1.4.18(@sinclair/typebox@0.34.41)(exact-mirror@0.2.5(@sinclair/typebox@0.34.41))(file-type@21.1.1)(openapi-types@12.1.3)(typescript@5.9.3))
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { CapacitorBarcodeScanner, CapacitorBarcodeScannerCameraDirection, CapacitorBarcodeScannerTypeHint } from "@capacitor/barcode-scanner";
|
||||
import { CapacitorBarcodeScanner, CapacitorBarcodeScannerCameraDirection, CapacitorBarcodeScannerScanOrientation, CapacitorBarcodeScannerTypeHint } from "@capacitor/barcode-scanner";
|
||||
import { toastController } from "@ionic/vue";
|
||||
|
||||
export interface QRScanResult {
|
||||
@@ -24,6 +24,7 @@ export function useQRScanner() {
|
||||
hint: CapacitorBarcodeScannerTypeHint.QR_CODE,
|
||||
scanInstructions: options?.title || t("scanner.hint"),
|
||||
cameraDirection: CapacitorBarcodeScannerCameraDirection.BACK,
|
||||
scanOrientation: CapacitorBarcodeScannerScanOrientation.PORTRAIT,
|
||||
});
|
||||
|
||||
vibrate();
|
||||
|
||||
@@ -385,6 +385,13 @@
|
||||
"yesterday": "Yesterday",
|
||||
"items": "items"
|
||||
},
|
||||
"fileUpload": {
|
||||
"uploadFile": "Upload File",
|
||||
"files": "files",
|
||||
"maxFilesError": "Maximum {max} files allowed",
|
||||
"fileSizeError": "File {name} exceeds {max}MB limit",
|
||||
"uploadError": "File {name} upload failed"
|
||||
},
|
||||
"auth": {
|
||||
"login": {
|
||||
"title": "Log in",
|
||||
|
||||
@@ -391,6 +391,13 @@
|
||||
"yesterday": "昨天",
|
||||
"items": "项"
|
||||
},
|
||||
"fileUpload": {
|
||||
"uploadFile": "上传文件",
|
||||
"files": "个文件",
|
||||
"maxFilesError": "最多只能上传 {max} 个文件",
|
||||
"fileSizeError": "文件 {name} 超过 {max}MB 限制",
|
||||
"uploadError": "文件 {name} 上传失败"
|
||||
},
|
||||
"auth": {
|
||||
"login": {
|
||||
"title": "登录",
|
||||
|
||||
@@ -1,10 +1,18 @@
|
||||
<script lang='ts' setup>
|
||||
import { documentAttachOutline, trashOutline } from "ionicons/icons";
|
||||
import type { UploadFetchOptions } from "@/utils/aws/s3";
|
||||
import { toastController } from "@ionic/vue";
|
||||
import { closeCircleOutline, documentAttachOutline, trashOutline } from "ionicons/icons";
|
||||
import { merge } from "lodash-es";
|
||||
import { uploadToS3 } from "@/utils/aws/s3";
|
||||
|
||||
interface FileItem {
|
||||
name: string;
|
||||
size: number;
|
||||
url?: string;
|
||||
fileId?: string; // S3 文件 ID
|
||||
uploading?: boolean;
|
||||
progress?: number;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
@@ -15,6 +23,7 @@ const props = withDefaults(defineProps<{
|
||||
multiple?: boolean;
|
||||
maxSize?: number; // MB
|
||||
maxFiles?: number;
|
||||
fetchOptions: Partial<UploadFetchOptions>;
|
||||
}>(), {
|
||||
modelValue: () => [],
|
||||
accept: "*/*",
|
||||
@@ -30,19 +39,24 @@ const emit = defineEmits<{
|
||||
const { t } = useI18n();
|
||||
const fileInput = ref<HTMLInputElement>();
|
||||
const files = ref<FileItem[]>([]);
|
||||
const abortControllers = new Map<number, AbortController>();
|
||||
|
||||
// 初始化已有文件
|
||||
watchEffect(() => {
|
||||
if (props.modelValue && props.modelValue.length > 0) {
|
||||
files.value = props.modelValue.map(url => ({
|
||||
name: url.split("/").pop() || "file",
|
||||
size: 0,
|
||||
url,
|
||||
}));
|
||||
files.value = props.modelValue.map((fileId) => {
|
||||
// 如果是完整 URL,提取文件名
|
||||
const name = fileId.includes("/") ? fileId.split("/").pop() || "file" : fileId;
|
||||
return {
|
||||
name,
|
||||
size: 0,
|
||||
fileId,
|
||||
};
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
function handleFileSelect(event: Event) {
|
||||
async function handleFileSelect(event: Event) {
|
||||
const input = event.target as HTMLInputElement;
|
||||
const selectedFiles = Array.from(input.files || []);
|
||||
|
||||
@@ -51,29 +65,71 @@ function handleFileSelect(event: Event) {
|
||||
|
||||
// 检查文件数量限制
|
||||
if (files.value.length + selectedFiles.length > props.maxFiles) {
|
||||
// TODO: 显示错误提示
|
||||
console.warn(`最多只能上传 ${props.maxFiles} 个文件`);
|
||||
await showToast(t("fileUpload.maxFilesError", { max: props.maxFiles }), "warning");
|
||||
return;
|
||||
}
|
||||
|
||||
selectedFiles.forEach((file) => {
|
||||
// 批量上传文件
|
||||
for (const file of selectedFiles) {
|
||||
// 检查文件大小
|
||||
if (file.size > props.maxSize * 1024 * 1024) {
|
||||
console.warn(`文件 ${file.name} 超过 ${props.maxSize}MB 限制`);
|
||||
return;
|
||||
await showToast(t("fileUpload.fileSizeError", { name: file.name, max: props.maxSize }), "warning");
|
||||
continue;
|
||||
}
|
||||
|
||||
// 创建预览 URL
|
||||
const url = URL.createObjectURL(file);
|
||||
files.value.push({
|
||||
// 添加到列表(显示上传中状态)
|
||||
const fileItem: FileItem = {
|
||||
name: file.name,
|
||||
size: file.size,
|
||||
url,
|
||||
});
|
||||
});
|
||||
uploading: true,
|
||||
progress: 0,
|
||||
};
|
||||
files.value.push(fileItem);
|
||||
const index = files.value.length - 1;
|
||||
|
||||
// 更新值
|
||||
updateValue();
|
||||
// 创建 AbortController
|
||||
const controller = new AbortController();
|
||||
abortControllers.set(index, controller);
|
||||
|
||||
try {
|
||||
// 上传到 S3
|
||||
const options = merge({
|
||||
fileName: file.name,
|
||||
fileSize: file.size,
|
||||
businessType: props.fetchOptions.businessType,
|
||||
}, props.fetchOptions) as UploadFetchOptions;
|
||||
|
||||
const fileId = await uploadToS3(file, {
|
||||
fetchOptions: options,
|
||||
onProgress: (progress) => {
|
||||
if (files.value[index]) {
|
||||
files.value[index].progress = progress;
|
||||
}
|
||||
},
|
||||
signal: controller.signal,
|
||||
});
|
||||
|
||||
// 上传成功
|
||||
if (files.value[index]) {
|
||||
files.value[index].fileId = String(fileId);
|
||||
files.value[index].uploading = false;
|
||||
files.value[index].progress = 100;
|
||||
abortControllers.delete(index);
|
||||
updateValue();
|
||||
}
|
||||
}
|
||||
catch (error: any) {
|
||||
// 上传失败或取消
|
||||
if (files.value[index]) {
|
||||
if (error.message !== "上传已取消") {
|
||||
files.value[index].error = error.message;
|
||||
files.value[index].uploading = false;
|
||||
await showToast(t("fileUpload.uploadError", { name: file.name }), "danger");
|
||||
}
|
||||
abortControllers.delete(index);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 重置 input
|
||||
if (fileInput.value) {
|
||||
@@ -82,17 +138,31 @@ function handleFileSelect(event: Event) {
|
||||
}
|
||||
|
||||
function removeFile(index: number) {
|
||||
const file = files.value[index];
|
||||
if (file.url && file.url.startsWith("blob:")) {
|
||||
URL.revokeObjectURL(file.url);
|
||||
// 如果正在上传,取消上传
|
||||
const controller = abortControllers.get(index);
|
||||
if (controller) {
|
||||
controller.abort();
|
||||
abortControllers.delete(index);
|
||||
}
|
||||
|
||||
files.value.splice(index, 1);
|
||||
updateValue();
|
||||
}
|
||||
|
||||
function cancelUpload(index: number) {
|
||||
const controller = abortControllers.get(index);
|
||||
if (controller) {
|
||||
controller.abort();
|
||||
abortControllers.delete(index);
|
||||
}
|
||||
removeFile(index);
|
||||
}
|
||||
|
||||
function updateValue() {
|
||||
const urls = files.value.map(f => f.url || "").filter(Boolean);
|
||||
emit("update:modelValue", urls);
|
||||
const fileIds = files.value
|
||||
.filter(f => f.fileId && !f.uploading && !f.error)
|
||||
.map(f => f.fileId!);
|
||||
emit("update:modelValue", fileIds);
|
||||
}
|
||||
|
||||
function formatFileSize(bytes: number): string {
|
||||
@@ -107,6 +177,22 @@ function formatFileSize(bytes: number): string {
|
||||
function triggerFileInput() {
|
||||
fileInput.value?.click();
|
||||
}
|
||||
|
||||
async function showToast(message: string, color: "success" | "warning" | "danger" = "warning") {
|
||||
const toast = await toastController.create({
|
||||
message,
|
||||
duration: 2000,
|
||||
position: "top",
|
||||
color,
|
||||
});
|
||||
await toast.present();
|
||||
}
|
||||
|
||||
// 组件卸载时清理
|
||||
onUnmounted(() => {
|
||||
abortControllers.forEach(controller => controller.abort());
|
||||
abortControllers.clear();
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -133,7 +219,7 @@ function triggerFileInput() {
|
||||
@click="triggerFileInput"
|
||||
>
|
||||
<ion-icon slot="start" :icon="documentAttachOutline" />
|
||||
{{ placeholder || t('common.uploadFile') }}
|
||||
{{ placeholder || t('fileUpload.uploadFile') }}
|
||||
</ion-button>
|
||||
|
||||
<!-- 文件列表 -->
|
||||
@@ -145,19 +231,49 @@ function triggerFileInput() {
|
||||
<div class="file-name">
|
||||
{{ file.name }}
|
||||
</div>
|
||||
<div v-if="file.size" class="file-size">
|
||||
<div v-if="file.size && !file.uploading" class="file-size">
|
||||
{{ formatFileSize(file.size) }}
|
||||
</div>
|
||||
|
||||
<!-- 上传进度 -->
|
||||
<div v-if="file.uploading" class="upload-progress">
|
||||
<ion-progress-bar :value="(file.progress || 0) / 100" color="primary" />
|
||||
<span class="progress-text">{{ file.progress }}%</span>
|
||||
</div>
|
||||
|
||||
<!-- 错误信息 -->
|
||||
<div v-if="file.error" class="error-text">
|
||||
{{ file.error }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<ion-button fill="clear" size="small" color="danger" @click="removeFile(index)">
|
||||
<ion-icon slot="icon-only" :icon="trashOutline" />
|
||||
</ion-button>
|
||||
|
||||
<!-- 操作按钮 -->
|
||||
<div class="file-actions">
|
||||
<ion-button
|
||||
v-if="file.uploading"
|
||||
fill="clear"
|
||||
size="small"
|
||||
color="medium"
|
||||
@click="cancelUpload(index)"
|
||||
>
|
||||
<ion-icon slot="icon-only" :icon="closeCircleOutline" />
|
||||
</ion-button>
|
||||
<ion-button
|
||||
v-else
|
||||
fill="clear"
|
||||
size="small"
|
||||
color="danger"
|
||||
@click="removeFile(index)"
|
||||
>
|
||||
<ion-icon slot="icon-only" :icon="trashOutline" />
|
||||
</ion-button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="files.length > 0" class="file-count">
|
||||
{{ files.length }} / {{ maxFiles }} {{ t('common.files') }}
|
||||
{{ files.filter(f => f.fileId).length }} / {{ maxFiles }} {{ t('fileUpload.files') }}
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -239,6 +355,38 @@ function triggerFileInput() {
|
||||
margin-top: 2px;
|
||||
}
|
||||
|
||||
.upload-progress {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-top: 4px;
|
||||
}
|
||||
|
||||
.upload-progress ion-progress-bar {
|
||||
flex: 1;
|
||||
height: 4px;
|
||||
}
|
||||
|
||||
.progress-text {
|
||||
font-size: 11px;
|
||||
color: var(--ion-color-primary);
|
||||
font-weight: 500;
|
||||
min-width: 35px;
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.error-text {
|
||||
font-size: 12px;
|
||||
color: var(--ion-color-danger);
|
||||
margin-top: 2px;
|
||||
}
|
||||
|
||||
.file-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.file-count {
|
||||
font-size: 12px;
|
||||
color: var(--ion-color-medium);
|
||||
|
||||
@@ -1,19 +1,77 @@
|
||||
import type { TreatyBody } from "@/api/types";
|
||||
import { client, safeClient } from "@/api";
|
||||
|
||||
interface PresignedUrlResponse {
|
||||
uploadUrl: string;
|
||||
fileUrl: string;
|
||||
key: string;
|
||||
expiresIn: number;
|
||||
}
|
||||
|
||||
interface UploadOptions {
|
||||
fetchOptions: UploadFetchOptions;
|
||||
onProgress?: (progress: number) => void;
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
|
||||
export function uploadToS3(file: File, options: UploadOptions = {}) {
|
||||
const { onProgress, signal } = options || {};
|
||||
export type UploadFetchOptions = TreatyBody<typeof client.api.file_storage.upload_url.post>;
|
||||
|
||||
export async function uploadToS3(file: File, options: UploadOptions) {
|
||||
const { onProgress, signal, fetchOptions } = options;
|
||||
|
||||
// 1. 获取预签名 URL
|
||||
const { data, error } = await safeClient(client.api.file_storage.upload_url.post({
|
||||
...fetchOptions,
|
||||
}));
|
||||
|
||||
if (error.value || !data.value) {
|
||||
throw new Error("获取上传 URL 失败");
|
||||
}
|
||||
const { fileId, uploadUrl, method, headers } = toRefs(data.value);
|
||||
|
||||
// 2. 上传文件到 S3
|
||||
return new Promise((resolve, reject) => {
|
||||
const xhr = new XMLHttpRequest();
|
||||
|
||||
// 监听上传进度
|
||||
xhr.upload.addEventListener("progress", (e: ProgressEvent) => {
|
||||
if (e.lengthComputable && onProgress) {
|
||||
const progress = Math.round((e.loaded / e.total) * 100);
|
||||
onProgress(progress);
|
||||
}
|
||||
});
|
||||
|
||||
// 上传成功
|
||||
xhr.addEventListener("load", () => {
|
||||
if (xhr.status >= 200 && xhr.status < 300) {
|
||||
resolve(fileId.value);
|
||||
}
|
||||
else {
|
||||
reject(new Error(`上传失败: ${xhr.status} ${xhr.statusText}`));
|
||||
}
|
||||
});
|
||||
|
||||
// 网络错误
|
||||
xhr.addEventListener("error", () => {
|
||||
reject(new Error("网络错误,上传失败"));
|
||||
});
|
||||
|
||||
// 上传取消
|
||||
xhr.addEventListener("abort", () => {
|
||||
reject(new Error("上传已取消"));
|
||||
});
|
||||
|
||||
// 超时
|
||||
xhr.addEventListener("timeout", () => {
|
||||
reject(new Error("上传超时"));
|
||||
});
|
||||
|
||||
// 支持外部取消
|
||||
if (signal) {
|
||||
signal.addEventListener("abort", () => {
|
||||
xhr.abort();
|
||||
});
|
||||
}
|
||||
|
||||
// 开始上传
|
||||
xhr.open(method.value, uploadUrl.value, true);
|
||||
for (const [key, value] of Object.entries(headers.value)) {
|
||||
xhr.setRequestHeader(key, value);
|
||||
}
|
||||
xhr.timeout = 300000; // 5分钟超时
|
||||
xhr.send(file);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -128,11 +128,15 @@ function handleSubmit(values: GenericObject) {
|
||||
<Field v-slot="{ field }" name="proofDocuments">
|
||||
<ui-file-upload
|
||||
v-bind="field"
|
||||
:fetch-options="{
|
||||
businessType: 'rwa_proof',
|
||||
}"
|
||||
:label="t('asset.issue.apply.assetProof')"
|
||||
:placeholder="t('asset.issue.apply.uploadAssetProof')"
|
||||
:max-files="5"
|
||||
:max-size="10"
|
||||
accept="application/pdf,image/*,.doc,.docx"
|
||||
@update:model-value="field.onChange($event.join(','))"
|
||||
/>
|
||||
</Field>
|
||||
<ErrorMessage name="proofDocuments" />
|
||||
|
||||
Reference in New Issue
Block a user