WMS_PDA/components/uploadImgCos/uploadImgCos.vue

697 lines
19 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<template>
<u-upload
ref="uUploadRef"
:fileList="fileList"
:maxCount="maxCount"
:multiple="multiple"
:disabled="disabled"
@afterRead="handleAfterRead"
@delete="handleDelete"
>
</u-upload>
</template>
<script>
export default {
name: "UploadImgCos",
props: {
business_type: {
type: String,
required: true
},
business_id: {
type: Number,
required: true
},
value: {
type: Array,
default: () => []
},
maxCount: {
type: Number,
default: 6
},
multiple: {
type: Boolean,
default: true
},
disabled: {
type: Boolean,
default: false
}
},
data() {
return {
internalFileList: [],
// 记录正在上传的文件,用于避免重复上传
uploadingFiles: new Set(),
// 记录最近一次getCOSUploadConfig请求使用的id(ReferenceFile必须使用该值)
lastUploadConfigRequestId: null
};
},
computed: {
fileList: {
get() {
return this.internalFileList;
},
set(value) {
this.internalFileList = value;
}
}
},
watch: {
value: {
immediate: true,
handler(newVal) {
this.formatFileList(newVal);
}
}
},
methods: {
/**
* 格式化文件列表
*/
formatFileList(externalList) {
if (!externalList || !Array.isArray(externalList)) {
this.internalFileList = [];
return;
}
this.internalFileList = externalList.map(item => {
if (item.status) {
return item;
}
return {
url: item.url || item.path || '',
name: item.name || this.extractFileName(item.url) || '',
status: 'success',
message: '',
id: item.id || item.fileId || ''
};
});
},
/**
* 提取文件名
*/
extractFileName(filePath) {
if (!filePath || typeof filePath !== 'string') return null;
return filePath.split(/[\\/]/).pop();
},
/**
* 解析本地可上传文件路径(相册/拍照兼容)
*/
resolveLocalFilePath(file) {
const candidates = [file?.path, file?.tempFilePath, file?.url, file?.thumb].filter(Boolean);
if (!candidates.length) {
return '';
}
const rawPath = String(candidates[0]);
try {
return decodeURIComponent(rawPath);
} catch (e) {
return rawPath;
}
},
/**
* 提取扩展名(不含.)
*/
extractExtension(value) {
if (!value || typeof value !== 'string') return '';
const cleanValue = value.split('?')[0].split('#')[0];
const baseName = cleanValue.split(/[\\/]/).pop() || '';
const match = baseName.match(/\.([a-z0-9]+)$/i);
return match ? match[1].toLowerCase() : '';
},
/**
* 解析图片扩展名(优先文件路径/文件名)
*/
resolveImageExtension(file, filePath = '') {
const fromPath = this.extractExtension(filePath || file?.url || file?.path || '');
if (['png', 'jpg', 'jpeg', 'webp', 'gif'].includes(fromPath)) {
return fromPath === 'jpeg' ? 'jpg' : fromPath;
}
const fromName = this.extractExtension(file?.name || '');
if (['png', 'jpg', 'jpeg', 'webp', 'gif'].includes(fromName)) {
return fromName === 'jpeg' ? 'jpg' : fromName;
}
const rawType = String(file?.type || '').toLowerCase();
if (rawType.includes('png')) return 'png';
if (rawType.includes('jpeg') || rawType.includes('jpg')) return 'jpg';
if (rawType.includes('webp')) return 'webp';
if (rawType.includes('gif')) return 'gif';
return 'jpg';
},
/**
* 提取上传配置返回的fileId
*/
resolveUploadConfigFileId(configData) {
if (!configData || typeof configData !== 'object') {
return '';
}
return configData.fileId || configData.file_id || configData?.fileInfo?.fileId || configData?.fileInfo?.file_id || '';
},
/**
* 解析上传地址(兼容不同后端字段)
*/
resolveUploadUrl(configData) {
if (!configData || typeof configData !== 'object') {
return '';
}
return configData.uploadUrl ||
configData.upload_url ||
configData.fileUrl ||
configData.file_url ||
configData.url ||
configData.postUrl ||
configData.post_url ||
configData?.fileInfo?.uploadUrl ||
configData?.fileInfo?.upload_url ||
configData?.fileInfo?.fileUrl ||
configData?.fileInfo?.file_url ||
'';
},
/**
* 归一化上传配置
*/
normalizeUploadConfig(rawUploadConfig, fallbackFileInfo) {
const primary = rawUploadConfig?.data && typeof rawUploadConfig.data === 'object'
? rawUploadConfig.data
: rawUploadConfig;
const nested = primary?.data && typeof primary.data === 'object' ? primary.data : null;
const source = nested || primary || {};
const uploadUrl = this.resolveUploadUrl(source) || this.resolveUploadUrl(primary) || this.resolveUploadUrl(rawUploadConfig);
const formData = source.data || source.formData || source.fields || source.params || {};
const fileInfo = source.fileInfo || primary?.fileInfo || fallbackFileInfo || {};
const fileId = this.resolveUploadConfigFileId(source) || this.resolveUploadConfigFileId(primary) || this.resolveUploadConfigFileId(rawUploadConfig);
const method = String(source.method || source.httpMethod || source.uploadMethod || source?.fileInfo?.method || '').toUpperCase();
const fileFieldName = source.fileFieldName || source.fieldName || source.fileField || source?.fileInfo?.fileFieldName || 'file';
const header = source.header || source.headers || source?.fileInfo?.header || source?.fileInfo?.headers || {};
return {
uploadUrl,
data: formData,
fileInfo,
fileId,
method: method || '',
fileFieldName,
header
};
},
/**
* 规范化图片MIME类型
*/
resolveImageMimeType(file) {
const extension = this.resolveImageExtension(file);
if (extension === 'png') return 'image/png';
if (extension === 'webp') return 'image/webp';
if (extension === 'gif') return 'image/gif';
return 'image/jpeg';
},
/**
* 确保文件名包含后缀
*/
ensureFileNameWithExtension(fileName, fileType, filePath = '') {
let normalizedName = String(fileName || '').trim();
if (!normalizedName) {
normalizedName = `image_${Date.now()}`;
}
const cleanName = normalizedName.split('?')[0].split('#')[0];
const expectedExt = `.${this.resolveImageExtension({ type: fileType, name: cleanName }, filePath)}`;
const hasExt = /\.[a-z0-9]+$/i.test(cleanName);
if (!hasExt) {
return `${cleanName}${expectedExt}`;
}
return cleanName.replace(/\.[a-z0-9]+$/i, expectedExt);
},
/**
* 获取文件MD5
*/
async getFileMd5(filePath) {
return new Promise((resolve, reject) => {
uni.getFileInfo({
filePath,
digestAlgorithm: "md5",
success: resolve,
fail: reject
});
});
},
/**
* 读取文件为ArrayBuffer(用于预签名PUT原始上传)
*/
readFileAsArrayBuffer(filePath) {
return new Promise((resolve, reject) => {
if (!uni.getFileSystemManager) {
reject(new Error('当前环境不支持文件系统读取'));
return;
}
const fileSystemManager = uni.getFileSystemManager();
fileSystemManager.readFile({
filePath,
encoding: 'binary',
success: (res) => {
resolve(res.data);
},
fail: (error) => {
reject(new Error(`读取文件失败: ${error?.errMsg || JSON.stringify(error)}`));
}
});
});
},
/**
* 预签名PUT原始二进制上传
*/
async uploadByRawPut(filePath, config) {
const fileBinary = await this.readFileAsArrayBuffer(filePath);
const requestHeader = {
'Content-Type': config?.fileInfo?.fileType || 'application/octet-stream',
...(config?.header || {})
};
return new Promise((resolve, reject) => {
uni.request({
url: config.uploadUrl,
method: 'PUT',
header: requestHeader,
data: fileBinary,
success: (res) => {
if (res.statusCode === 200 || res.statusCode === 201 || res.statusCode === 204) {
resolve();
return;
}
reject(new Error(`COS原始PUT上传失败,状态码: ${res.statusCode}, 响应: ${typeof res.data === 'string' ? res.data : JSON.stringify(res.data)}`));
},
fail: (error) => {
reject(new Error(`COS原始PUT请求失败: ${error?.errMsg || JSON.stringify(error)}`));
}
});
});
},
/**
* 处理文件选择
*/
async handleAfterRead(event) {
if (this.disabled) return;
const { file, name } = event;
const files = Array.isArray(file) ? file : [file];
// 检查数量限制
const remainingSlots = this.maxCount - this.fileList.length;
if (remainingSlots <= 0) {
uni.showToast({
title: `最多只能上传${this.maxCount}个文件`,
icon: 'none'
});
return;
}
const filesToUpload = files.slice(0, remainingSlots);
// 添加文件到列表(初始状态为pending)
const startIndex = this.fileList.length;
filesToUpload.forEach((file) => {
this.fileList.push({
...file,
status: "pending",
message: "等待上传"
});
});
// 串行上传
for (let i = 0; i < filesToUpload.length; i++) {
const fileIndex = startIndex + i;
await this.processFileUpload(filesToUpload[i], fileIndex);
}
},
/**
* 处理单个文件上传流程
*/
async processFileUpload(file, fileIndex) {
try {
// 检查是否已经在上传
const localFilePath = this.resolveLocalFilePath(file);
if (!localFilePath) {
throw new Error('未获取到可上传的本地文件路径');
}
const fileKey = `${localFilePath}_${file.size}`;
if (this.uploadingFiles.has(fileKey)) {
return;
}
this.uploadingFiles.add(fileKey);
// 1. 获取文件MD5
const fileInfo = await this.getFileMd5(localFilePath);
const fileType = this.resolveImageMimeType(file);
const rawFileName = this.extractFileName(localFilePath) || file.name;
const fileName = this.ensureFileNameWithExtension(rawFileName, fileType, localFilePath);
const requestBusinessId = this.business_id;
// 2. 更新状态为上传中
this.fileList[fileIndex] = {
...file,
status: "uploading",
message: "上传中",
md5: fileInfo.digest
};
// 3. 获取COS上传配置
const getCosUploadConfigPayload = {
fileName,
fileSize: fileInfo.size,
fileType,
id: requestBusinessId,
md5: fileInfo.digest,
type: this.business_type,
};
console.log('[API] index.getCOSUploadConfig request:', getCosUploadConfigPayload);
const uploadConfig = await this.$http('common.getCOSUploadConfig', {
data: getCosUploadConfigPayload
});
console.log('[API] index.getCOSUploadConfig response:', uploadConfig);
const fallbackFileInfo = {
fileName,
fileSize: fileInfo.size,
fileType,
md5: fileInfo.digest
};
const configData = this.normalizeUploadConfig(uploadConfig, fallbackFileInfo);
console.log('[API] normalized COS config:', configData);
if (!configData || !configData.uploadUrl) {
console.error('[API] getCOSUploadConfig invalid response:', uploadConfig);
throw new Error("获取上传配置失败");
}
const uploadConfigFileId = configData.fileId;
if (!uploadConfigFileId) {
console.warn('[API] index.getCOSUploadConfig response missing fileId, will fallback to index.uploadSuccessNotify fileId');
}
this.lastUploadConfigRequestId = requestBusinessId;
// 4. 执行COS上传(这里不会返回响应数据)
await this.uploadToCOS(localFilePath, configData, fileIndex);
// 5. 通知后端上传完成
const notifyResult = await this.notifyUploadComplete(configData.fileInfo, fileIndex);
// 6. 更新状态为成功
if (notifyResult.data?.data) {
const { fileUrl, fileId: notifyFileId, file_id: notifyFileIdAlt } = notifyResult.data.data;
const finalFileId = uploadConfigFileId || notifyFileId || notifyFileIdAlt || '';
if (!finalFileId) {
throw new Error('上传成功但未获取到fileId');
}
this.fileList[fileIndex] = {
...this.fileList[fileIndex],
status: "success",
message: "",
url: fileUrl,
id: finalFileId,
uploadConfigRequestId: requestBusinessId,
successUrl: fileUrl // 保存成功后的URL
};
// 7. 关联文件
await this.referenceFiles();
// 触发成功事件
this.$emit('upload-success', {
file: this.fileList[fileIndex],
index: fileIndex
});
}
} catch (error) {
console.error("上传流程失败:", error);
console.error('[API] index.getCOSUploadConfig/reference flow error:', error);
this.fileList[fileIndex] = {
...this.fileList[fileIndex],
status: "error",
message: error.message || "上传失败"
};
} finally {
// 清理上传记录
const localFilePath = this.resolveLocalFilePath(file);
const fileKey = `${localFilePath}_${file.size}`;
this.uploadingFiles.delete(fileKey);
}
},
/**
* 上传文件到COS(关键修改:不需要处理响应)
*/
uploadToCOS(filePath, config, fileIndex) {
return new Promise((resolve, reject) => {
if (!config?.uploadUrl) {
reject(new Error('COS上传地址为空(uploadUrl)'));
return;
}
const normalizedUploadUrl = String(config.uploadUrl || '').trim();
const hasFormData = !!(config?.data && Object.keys(config.data).length);
const preferredMethod = config?.method || (hasFormData ? 'POST' : 'PUT');
const fallbackMethod = preferredMethod === 'POST' ? 'PUT' : 'POST';
const shouldTryRawPut = !hasFormData && preferredMethod === 'PUT';
console.log('[API] COS upload request:', {
uploadUrl: normalizedUploadUrl,
filePath,
method: preferredMethod,
fallbackMethod,
fileFieldName: config?.fileFieldName || 'file',
header: config?.header || {},
formData: config?.data || {},
fileName: config?.fileInfo?.fileName,
fileType: config?.fileInfo?.fileType
});
const tryUpload = (method) => new Promise((uploadResolve, uploadReject) => {
const uploadTask = uni.uploadFile({
url: normalizedUploadUrl,
filePath: filePath,
name: config?.fileFieldName || 'file',
formData: config?.data || {},
header: config?.header || {},
method,
success: (res) => {
if (res.statusCode === 200 || res.statusCode === 201 || res.statusCode === 204) {
uploadResolve();
} else {
uploadReject(new Error(`COS上传失败,状态码: ${res.statusCode}, 响应: ${typeof res.data === 'string' ? res.data : JSON.stringify(res.data)}`));
}
},
fail: (error) => {
uploadReject(new Error(`COS上传请求失败: ${error?.errMsg || JSON.stringify(error) || 'unknown error'}`));
}
});
uploadTask.onProgressUpdate((res) => {
this.fileList[fileIndex] = {
...this.fileList[fileIndex],
progress: res.progress,
message: `上传中 ${res.progress}%`
};
this.$emit('upload-progress', {
index: fileIndex,
progress: res.progress,
totalBytesSent: res.totalBytesSent,
totalBytesExpectedToSend: res.totalBytesExpectedToSend
});
});
});
const runUploadFileFallback = () => {
tryUpload(preferredMethod)
.then(resolve)
.catch((firstError) => {
console.error('[API] COS upload fail detail:', firstError);
console.warn(`[API] COS upload retry with method: ${fallbackMethod}`);
tryUpload(fallbackMethod)
.then(resolve)
.catch((secondError) => {
console.error('[API] COS upload retry fail detail:', secondError);
reject(secondError);
});
});
};
if (shouldTryRawPut) {
console.log('[API] COS raw PUT upload attempt');
this.uploadByRawPut(filePath, config)
.then(resolve)
.catch((rawError) => {
console.error('[API] COS raw PUT upload fail detail:', rawError);
runUploadFileFallback();
});
return;
}
runUploadFileFallback();
});
},
/**
* 通知后端上传完成
*/
async notifyUploadComplete(config, fileIndex) {
try {
// 调用后端接口,通知COS上传已完成
const response = await this.$http('common.uploadSuccessNotify', {
...config,
fileInfo: {
fileName: config.fileName,
fileSize: config.fileSize,
fileType: config.fileType,
md5: config.md5
}
});
return response;
} catch (error) {
console.error("上传完成通知失败:", error);
throw error;
}
},
/**
* 关联文件
*/
async referenceFiles() {
console.log("this.fileList",this.fileList);
try {
const referenceId = this.lastUploadConfigRequestId || this.business_id;
// 获取所有成功的文件(包括之前已经关联的)
const validFiles = this.fileList
.filter(item => item.status === "success" && item.id)
.map(item => ({ file_id: item.id }));
if (validFiles.length === 0) {
const referencePayload = {
id: referenceId,
type: this.business_type,
images: []
};
console.log('[API] index.ReferenceFile request:', referencePayload);
// 如果没有成功文件,也要通知后端清空关联
const response = await this.$http('common.ReferenceFile', {
...referencePayload
});
console.log('[API] index.ReferenceFile response:', response);
// 更新外部绑定
this.$emit('change', this.fileList);
this.$emit('input', this.fileList);
return response;
}
const referencePayload = {
id: referenceId,
type: this.business_type,
images: validFiles
};
console.log('[API] index.ReferenceFile request:', referencePayload);
const response = await this.$http('common.ReferenceFile', {
...referencePayload
});
console.log('[API] index.ReferenceFile response:', response);
// 更新外部绑定
this.$emit('change', this.fileList);
this.$emit('input', this.fileList);
return response;
} catch (error) {
console.error("关联文件失败:", error);
console.error('[API] index.ReferenceFile error:', error);
throw error;
}
},
/**
* 处理删除 - 修正版本
*/
async handleDelete(index) {
const deletedFile = this.fileList[index];
// 从列表中移除
this.fileList.splice(index, 1);
// 立即更新UI
this.$emit('delete', {
file: deletedFile,
index
});
// 更新外部绑定(立即更新,不等待)
this.$emit('change', this.fileList);
this.$emit('input', this.fileList);
// 异步更新文件关联
try {
await this.referenceFiles();
} catch (error) {
console.error("删除后重新关联失败:", error);
// 这里可以选择给用户提示,但不阻塞UI
}
},
/**
* 手动上传
*/
upload() {
if (this.$refs.uUploadRef && !this.disabled) {
this.$refs.uUploadRef.chooseFile();
}
},
/**
* 获取上传成功的文件
*/
getSuccessFiles() {
return this.fileList.filter(item => item.status === "success");
},
/**
* 清空文件
*/
clearFiles() {
this.fileList = [];
this.$emit('input', []);
this.$emit('change', []);
}
}
};
</script>
<style scoped>
</style>