fix(upload): 调整COS上传流程实现

This commit is contained in:
zm2000 2026-04-22 18:03:25 +08:00
parent af356d2ba2
commit 72179ce679

View File

@ -44,9 +44,7 @@ export default {
return {
internalFileList: [],
// 记录正在上传的文件,用于避免重复上传
uploadingFiles: new Set(),
// 记录最近一次getCOSUploadConfig请求使用的id(ReferenceFile必须使用该值)
lastUploadConfigRequestId: null
uploadingFiles: new Set()
};
},
computed: {
@ -100,150 +98,6 @@ export default {
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
*/
@ -258,60 +112,6 @@ export default {
});
},
/**
* 读取文件为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)}`));
}
});
});
},
/**
@ -335,7 +135,7 @@ export default {
const filesToUpload = files.slice(0, remainingSlots);
// 添加文件到列表(初始状态为pending)
// 添加文件到列表(初始状态为pending)
const startIndex = this.fileList.length;
filesToUpload.forEach((file) => {
this.fileList.push({
@ -358,11 +158,7 @@ export default {
async processFileUpload(file, fileIndex) {
try {
// 检查是否已经在上传
const localFilePath = this.resolveLocalFilePath(file);
if (!localFilePath) {
throw new Error('未获取到可上传的本地文件路径');
}
const fileKey = `${localFilePath}_${file.size}`;
const fileKey = `${file.url}_${file.size}`;
if (this.uploadingFiles.has(fileKey)) {
return;
}
@ -370,11 +166,8 @@ export default {
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;
const fileInfo = await this.getFileMd5(file.url);
const fileName = this.extractFileName(file.url) || file.name;
// 2. 更新状态为上传中
this.fileList[fileIndex] = {
@ -385,39 +178,23 @@ export default {
};
// 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
data: {
fileName,
fileSize: fileInfo.size,
fileType: file.type,
id: this.business_id,
md5: fileInfo.digest,
type: this.business_type,
}
});
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);
const configData = uploadConfig.data;
if (!configData) {
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);
// 4. 执行COS上传(这里不会返回响应数据)
await this.uploadToCOS(file.url, configData, fileIndex);
// 5. 通知后端上传完成
@ -425,18 +202,13 @@ export default {
// 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');
}
const { fileUrl, fileId } = notifyResult.data.data;
this.fileList[fileIndex] = {
...this.fileList[fileIndex],
status: "success",
message: "",
url: fileUrl,
id: finalFileId,
uploadConfigRequestId: requestBusinessId,
id: fileId,
successUrl: fileUrl // 保存成功后的URL
};
@ -451,7 +223,6 @@ export default {
} catch (error) {
console.error("上传流程失败:", error);
console.error('[API] index.getCOSUploadConfig/reference flow error:', error);
this.fileList[fileIndex] = {
...this.fileList[fileIndex],
status: "error",
@ -459,102 +230,52 @@ export default {
};
} finally {
// 清理上传记录
const localFilePath = this.resolveLocalFilePath(file);
const fileKey = `${localFilePath}_${file.size}`;
const fileKey = `${file.url}_${file.size}`;
this.uploadingFiles.delete(fileKey);
}
},
/**
* 上传文件到COS(关键修改:不需要处理响应)
* 上传文件到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'}`));
// COS上传不会返回数据,所以这里只是发起请求
const uploadTask = uni.uploadFile({
url: config.uploadUrl, // 应该从config中获取
filePath: filePath,
name: 'file',
formData: config.data,
// COS上传成功不会有响应体,只会有状态码
success: (res) => {
// 注意:COS返回的HTTP状态码成功通常是204或200,但没有响应体
if (res.statusCode === 200 || res.statusCode === 204) {
resolve();
} else {
reject(new Error(`COS上传失败,状态码: ${res.statusCode}`));
}
});
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
});
});
},
fail: (error) => {
reject(new Error("COS上传请求失败"));
}
});
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);
});
});
// 可以监听上传进度
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
});
};
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();
});
},
@ -586,25 +307,18 @@ export default {
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
id: this.business_id,
type: this.business_type,
images: []
});
console.log('[API] index.ReferenceFile response:', response);
// 更新外部绑定
this.$emit('change', this.fileList);
@ -612,16 +326,11 @@ export default {
return response;
}
const referencePayload = {
id: referenceId,
const response = await this.$http('common.ReferenceFile', {
id: this.business_id,
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);
@ -630,7 +339,6 @@ export default {
return response;
} catch (error) {
console.error("关联文件失败:", error);
console.error('[API] index.ReferenceFile error:', error);
throw error;
}
},