WMS_PDA/components/uploadImgCos/uploadImgCos.vue

921 lines
24 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: [],
knownFileIds: [],
// 记录正在上传的文件,用于避免重复上传
uploadingFiles: new Set()
};
},
computed: {
fileList: {
get() {
return this.internalFileList;
},
set(value) {
this.internalFileList = value;
}
}
},
watch: {
business_id: {
immediate: true,
handler() {
this.knownFileIds = [];
}
},
value: {
immediate: true,
handler(newVal) {
this.formatFileList(newVal);
}
}
},
methods: {
resolveDeleteIndex(payload) {
const normalizeIndex = (value) => {
const numeric = Number(value);
if (!Number.isFinite(numeric)) {
return -1;
}
const index = Math.trunc(numeric);
return index >= 0 ? index : -1;
};
if (typeof payload === 'number' || typeof payload === 'string') {
return normalizeIndex(payload);
}
if (!payload || typeof payload !== 'object') {
return -1;
}
const directIndex = normalizeIndex(payload.index);
if (directIndex >= 0) {
return directIndex;
}
const detailIndex = normalizeIndex(payload.detail && payload.detail.index);
if (detailIndex >= 0) {
return detailIndex;
}
const file = payload.file || (payload.detail && payload.detail.file) || null;
if (!file || typeof file !== 'object') {
return -1;
}
const fileId = this.getFileId(file);
if (fileId) {
const byIdIndex = this.fileList.findIndex(item => this.getFileId(item) === fileId);
if (byIdIndex >= 0) {
return byIdIndex;
}
}
const fileUrl = file.url || file.path || file.successUrl || '';
if (fileUrl) {
return this.fileList.findIndex(item => (item.url || item.path || item.successUrl || '') === fileUrl);
}
return -1;
},
getFileId(file) {
if (!file || typeof file !== 'object') {
return '';
}
return file.id || file.fileId || file.file_id || (file.file && (file.file.id || file.file.fileId || file.file.file_id)) || '';
},
normalizeNumericFileIds(fileIds = []) {
return Array.from(new Set((Array.isArray(fileIds) ? fileIds : [fileIds])
.map(fileId => Number(fileId))
.filter(fileId => Number.isFinite(fileId) && fileId > 0)));
},
collectFileIdsFromList(fileList = []) {
if (!Array.isArray(fileList)) {
return [];
}
return this.normalizeNumericFileIds(fileList.map(item => this.getFileId(item)));
},
mergeKnownFileIds(fileIds = []) {
this.knownFileIds = this.normalizeNumericFileIds([...(this.knownFileIds || []), ...fileIds]);
},
replaceKnownFileIds(fileIds = []) {
this.knownFileIds = this.normalizeNumericFileIds(fileIds);
},
extractImageListFromGetImagesResponse(response) {
if (!response || typeof response !== 'object') {
return [];
}
const candidates = [
response.data,
response.data && response.data.data,
response.data && response.data.images,
response.data && response.data.list,
response.data && response.data.rows,
response.data && response.data.records,
response.data && response.data.result,
response.data && response.data.result && response.data.result.images,
response.data && response.data.result && response.data.result.list,
response.images,
response.list,
response.rows,
response.records
];
for (let i = 0; i < candidates.length; i++) {
const current = candidates[i];
if (!current) {
continue;
}
if (Array.isArray(current)) {
return current;
}
if (typeof current === 'object') {
const objectCandidates = [current.images, current.list, current.rows, current.records, current.data];
for (let j = 0; j < objectCandidates.length; j++) {
if (Array.isArray(objectCandidates[j])) {
return objectCandidates[j];
}
}
}
}
return [];
},
getRemoteFileId(file) {
if (!file || typeof file !== 'object') {
return '';
}
return file.file_id
|| file.fileId
|| file.id
|| file.image_id
|| (file.file && (file.file.file_id || file.file.fileId || file.file.id))
|| '';
},
normalizeFileUrl(url) {
if (!url || typeof url !== 'string') {
return '';
}
const trimmed = url.trim();
if (!trimmed) {
return '';
}
return trimmed.split('?')[0].split('#')[0];
},
getFileUrlSignature(url) {
const normalizedUrl = this.normalizeFileUrl(url);
if (!normalizedUrl) {
return '';
}
const withoutProtocol = normalizedUrl.replace(/^https?:\/\//i, '');
const pathWithHost = withoutProtocol.split('/');
if (pathWithHost.length <= 1) {
return withoutProtocol.toLowerCase();
}
const pathOnly = '/' + pathWithHost.slice(1).join('/');
const pathParts = pathOnly.split('/').filter(Boolean);
if (!pathParts.length) {
return pathOnly.toLowerCase();
}
const tail = pathParts.slice(-2).join('/').toLowerCase();
return tail || pathOnly.toLowerCase();
},
getRemoteFileUrl(file) {
if (!file || typeof file !== 'object') {
return '';
}
return this.normalizeFileUrl(
file.url
|| file.path
|| file.fileUrl
|| file.image_url
|| file.img_url
|| file.src
|| (file.file && (file.file.url || file.file.path || file.file.fileUrl))
|| ''
);
},
async getRemoteImageEntries() {
if (!this.business_id) {
return [];
}
const response = await this.$http('common.getImages', {
id: Number(this.business_id),
business_id: Number(this.business_id),
stock_id: Number(this.business_id),
type: this.business_type,
business_type: this.business_type
});
const entries = this.extractImageListFromGetImagesResponse(response)
.map(item => ({
fileId: this.getRemoteFileId(item),
url: this.getRemoteFileUrl(item)
}))
.filter(item => item.fileId || item.url);
this.mergeKnownFileIds(entries.map(item => item.fileId));
return entries;
},
async getRemoteFileIds() {
if (!this.business_id) {
return [];
}
try {
return (await this.getRemoteImageEntries())
.map(item => item.fileId)
.filter(Boolean);
} catch (error) {
if (process.env.NODE_ENV !== 'production') {
console.warn('[UploadImgCos] getRemoteFileIds failed', error);
}
return [];
}
},
async resolveDeletedFileIds(deletedFile, options = {}) {
const deletedIndex = Number(options.deletedIndex);
const hasValidDeletedIndex = Number.isFinite(deletedIndex) && deletedIndex >= 0;
const deletedIds = [];
const directId = this.getFileId(deletedFile);
if (directId) {
deletedIds.push(directId);
}
if (deletedIds.length > 0) {
return Array.from(new Set(deletedIds));
}
const deletedUrl = this.normalizeFileUrl(
(deletedFile && (deletedFile.url || deletedFile.path || deletedFile.successUrl)) || ''
);
const deletedUrlSignature = this.getFileUrlSignature(deletedUrl);
if (!deletedUrl) {
if (!hasValidDeletedIndex) {
return [];
}
}
try {
const remoteEntries = await this.getRemoteImageEntries();
let matched = remoteEntries
.filter(item => item.fileId && item.url && item.url === deletedUrl)
.map(item => item.fileId);
if (!matched.length && deletedUrlSignature) {
matched = remoteEntries
.filter(item => item.fileId && this.getFileUrlSignature(item.url) === deletedUrlSignature)
.map(item => item.fileId);
}
if (!matched.length && hasValidDeletedIndex && remoteEntries[deletedIndex] && remoteEntries[deletedIndex].fileId) {
matched = [remoteEntries[deletedIndex].fileId];
}
return Array.from(new Set(matched));
} catch (error) {
if (process.env.NODE_ENV !== 'production') {
console.warn('[UploadImgCos] resolveDeletedFileIds failed', error);
}
return [];
}
},
/**
* 格式化文件列表
*/
formatFileList(externalList) {
if (!externalList || !Array.isArray(externalList)) {
this.internalFileList = [];
return;
}
this.internalFileList = externalList.map(item => {
if (item.status) {
return {
...item,
id: this.getFileId(item)
};
}
return {
url: item.url || item.path || '',
name: item.name || this.extractFileName(item.url) || '',
status: 'success',
message: '',
id: this.getFileId(item)
};
});
const listFileIds = this.collectFileIdsFromList(this.internalFileList);
if (listFileIds.length > 0) {
this.mergeKnownFileIds(listFileIds);
}
},
/**
* 提取文件名
*/
extractFileName(filePath) {
if (!filePath || typeof filePath !== 'string') return null;
return filePath.split(/[\\/]/).pop();
},
/**
* 获取文件MD5
*/
async getFileMd5(filePath) {
return new Promise((resolve, reject) => {
uni.getFileInfo({
filePath,
digestAlgorithm: "md5",
success: resolve,
fail: reject
});
});
},
/**
* 处理文件选择
*/
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 fileKey = `${file.url}_${file.size}`;
if (this.uploadingFiles.has(fileKey)) {
return;
}
this.uploadingFiles.add(fileKey);
// 1. 获取文件MD5
const fileInfo = await this.getFileMd5(file.url);
const fileName = this.extractFileName(file.url) || file.name;
// 2. 更新状态为上传中
this.fileList[fileIndex] = {
...file,
status: "uploading",
message: "上传中",
md5: fileInfo.digest
};
// 3. 获取COS上传配置
const uploadConfig = await this.$http('common.getCOSUploadConfig', {
data: {
fileName,
fileSize: fileInfo.size,
fileType: file.type,
id: this.business_id,
md5: fileInfo.digest,
type: this.business_type,
}
});
const configData = uploadConfig.data;
if (!configData) {
throw new Error("获取上传配置失败");
}
console.log(configData);
if(configData.fileId){
// 如果后端已经返回了fileId,说明文件已存在,无需上传,直接通知后端关联即可
this.fileList[fileIndex] = {
...this.fileList[fileIndex],
status: "success",
message: "",
url: configData.fileUrl,
id: configData.fileId,
successUrl: configData.fileUrl // 保存成功后的URL
};
await this.referenceFiles({
source: 'upload'
});
return ;
}
// 4. 执行COS上传(这里不会返回响应数据)
await this.uploadToCOS(file.url, configData, fileIndex);
// 5. 通知后端上传完成
const notifyResult = await this.notifyUploadComplete(configData.fileInfo, fileIndex);
console.log("后端上传成功返回",JSON.stringify(notifyResult));
// 6. 更新状态为成功
if (notifyResult.data?.data) {
const { fileUrl, fileId } = notifyResult.data.data;
this.fileList[fileIndex] = {
...this.fileList[fileIndex],
status: "success",
message: "",
url: fileUrl,
id: fileId,
successUrl: fileUrl // 保存成功后的URL
};
// 7. 关联文件
await this.referenceFiles({
source: 'upload'
});
// 触发成功事件
this.$emit('upload-success', {
file: this.fileList[fileIndex],
index: fileIndex
});
}
} catch (error) {
console.error("上传流程失败:", error);
this.fileList[fileIndex] = {
...this.fileList[fileIndex],
status: "error",
message: error.message || "上传失败"
};
} finally {
// 清理上传记录
const fileKey = `${file.url}_${file.size}`;
this.uploadingFiles.delete(fileKey);
}
},
/**
* 上传文件到COS(关键修改:不需要处理响应)
*/
uploadToCOS(filePath, config, fileIndex) {
return new Promise((resolve, reject) => {
// 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}`));
}
},
fail: (error) => {
reject(new Error("COS上传请求失败"));
}
});
// 可以监听上传进度
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
});
};
});
},
/**
* 通知后端上传完成
*/
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(options = {}) {
const { mergeRemote = true, excludedFileIds = [], excludedFileUrls = [], source = '', explicitFileIds = null } = options;
console.log("this.fileList",this.fileList);
try {
const explicitIds = Array.isArray(explicitFileIds)
? explicitFileIds
.map(fileId => Number(fileId))
.filter(fileId => Number.isFinite(fileId) && fileId > 0)
: null;
if (explicitIds) {
const validFiles = Array.from(new Set(explicitIds)).map(fileId => ({ file_id: fileId }));
if (process.env.NODE_ENV !== 'production') {
console.log('[UploadImgCos] ReferenceFile payload debug', {
source,
business_id: this.business_id,
type: this.business_type,
explicit_file_ids: validFiles.map(item => item.file_id)
});
}
const requestPayload = {
id: this.business_id,
type: this.business_type,
images: validFiles
};
console.log('[UploadImgCos] ReferenceFile request', {
source,
payload: requestPayload
});
const response = await this.$http('common.ReferenceFile', requestPayload);
console.log('[UploadImgCos] ReferenceFile response', {
source,
response
});
this.replaceKnownFileIds(validFiles.map(item => item.file_id));
this.$emit('change', this.fileList);
this.$emit('input', this.fileList);
return response;
}
// 获取当前本地成功文件(以本地列表为准)
const localEntries = this.fileList
.filter(item => {
const status = String((item && item.status) || '').toLowerCase();
if (!status) {
return true;
}
return status !== 'uploading' && status !== 'pending' && status !== 'error';
})
.map(item => ({
fileId: this.getFileId(item),
url: this.normalizeFileUrl(item.url || item.path || item.successUrl || '')
}));
const remoteEntries = mergeRemote ? await this.getRemoteImageEntries() : [];
const remoteFileIds = (remoteEntries || []).map(item => item.fileId).filter(Boolean);
const localFileIds = (localEntries || []).map(item => item.fileId).filter(Boolean);
const knownFileIds = this.normalizeNumericFileIds(this.knownFileIds || []);
const excludedSet = new Set(
(Array.isArray(excludedFileIds) ? excludedFileIds : [excludedFileIds])
.filter(Boolean)
.map(fileId => String(fileId))
);
const excludedUrlSet = new Set(
(Array.isArray(excludedFileUrls) ? excludedFileUrls : [excludedFileUrls])
.map(url => this.normalizeFileUrl(url))
.filter(Boolean)
);
// 优先使用本地已有file_id;若本地项缺失file_id,则按URL从远端补全
const localUrlSet = new Set(
localEntries
.map(item => this.normalizeFileUrl(item.url || ''))
.filter(Boolean)
);
const recoveredFileIds = mergeRemote
? (remoteEntries || [])
.filter(item => {
const normalizedUrl = this.normalizeFileUrl(item && item.url ? item.url : '');
return normalizedUrl && localUrlSet.has(normalizedUrl);
})
.map(item => item.fileId)
.filter(Boolean)
: [];
const shouldKeepAllRemoteIds = mergeRemote && source !== 'delete';
const candidateFileIds = shouldKeepAllRemoteIds
? [...knownFileIds, ...(remoteFileIds || []), ...(localFileIds || [])]
: [...knownFileIds, ...(localFileIds || []), ...(recoveredFileIds || [])];
const mergedFileIds = Array.from(new Set(candidateFileIds
.map(fileId => String(fileId))
.filter(Boolean)))
.filter(fileId => !excludedSet.has(fileId))
.map(fileId => Number(fileId))
.filter(fileId => Number.isFinite(fileId) && fileId > 0);
const validFiles = mergedFileIds.map(fileId => ({ file_id: fileId }));
if (process.env.NODE_ENV !== 'production') {
console.log('[UploadImgCos] ReferenceFile payload debug', {
source,
business_id: this.business_id,
type: this.business_type,
merge_remote: mergeRemote,
excluded_file_ids: Array.from(excludedSet),
excluded_file_urls: Array.from(excludedUrlSet),
remote_file_ids: remoteFileIds,
local_file_ids: localFileIds,
file_ids: validFiles.map(item => item.file_id),
file_list: this.fileList.map(item => ({
url: item.url || item.path || item.successUrl || '',
status: item.status,
id: this.getFileId(item)
}))
});
}
if (validFiles.length === 0) {
// 如果没有成功文件,也要通知后端清空关联
const requestPayload = {
id: this.business_id,
type: this.business_type,
images: []
};
console.log('[UploadImgCos] ReferenceFile request', {
source,
payload: requestPayload
});
const response = await this.$http('common.ReferenceFile', requestPayload);
console.log('[UploadImgCos] ReferenceFile response', {
source,
response
});
this.replaceKnownFileIds([]);
// 更新外部绑定
this.$emit('change', this.fileList);
this.$emit('input', this.fileList);
return response;
}
const requestPayload = {
id: this.business_id,
type: this.business_type,
images: validFiles
};
console.log('[UploadImgCos] ReferenceFile request', {
source,
payload: requestPayload
});
const response = await this.$http('common.ReferenceFile', requestPayload);
console.log('[UploadImgCos] ReferenceFile response', {
source,
response
});
this.replaceKnownFileIds(validFiles.map(item => item.file_id));
// 更新外部绑定
this.$emit('change', this.fileList);
this.$emit('input', this.fileList);
return response;
} catch (error) {
console.error("关联文件失败:", error);
throw error;
}
},
/**
* 处理删除 - 修正版本
*/
async handleDelete(payload) {
const index = this.resolveDeleteIndex(payload);
if (index < 0 || index >= this.fileList.length) {
console.warn('[UploadImgCos] 删除图片失败:无法定位删除项', payload);
return;
}
const deletedFile = this.fileList[index];
const deletedFileUrl = this.normalizeFileUrl(
(deletedFile && (deletedFile.url || deletedFile.path || deletedFile.successUrl)) || ''
);
// 从列表中移除
this.fileList.splice(index, 1);
// 立即更新UI
this.$emit('delete', {
file: deletedFile,
index
});
// 更新外部绑定(立即更新,不等待)
this.$emit('change', this.fileList);
this.$emit('input', this.fileList);
// 异步更新文件关联:删除场景显式提交“剩余file_id”,避免误清空
try {
const remoteEntries = await this.getRemoteImageEntries();
const deletedFileIds = await this.resolveDeletedFileIds(deletedFile, {
deletedIndex: index
});
const deletedIdSet = new Set((deletedFileIds || []).map(fileId => String(fileId)).filter(Boolean));
const deletedDirectId = String(this.getFileId(deletedFile) || '').trim();
if (deletedDirectId) {
deletedIdSet.add(deletedDirectId);
}
const remoteAllIds = this.normalizeNumericFileIds((remoteEntries || []).map(item => item && item.fileId));
const knownAllIds = this.normalizeNumericFileIds(this.knownFileIds || []);
let finalFileIds = remoteAllIds.length > 0
? remoteAllIds.filter(fileId => !deletedIdSet.has(String(fileId)))
: knownAllIds.filter(fileId => !deletedIdSet.has(String(fileId)));
if (this.fileList.length > 0 && finalFileIds.length === 0) {
console.warn('[UploadImgCos] 删除后未能可靠计算剩余file_id,已阻止空关联提交', {
deleted_file_ids: deletedFileIds,
deleted_file_url: deletedFileUrl,
remote_entries_count: Array.isArray(remoteEntries) ? remoteEntries.length : 0,
remote_all_ids: remoteAllIds,
known_all_ids: knownAllIds,
known_file_ids_count: Array.isArray(this.knownFileIds) ? this.knownFileIds.length : 0
});
// 回滚UI,避免前端显示与后端实际不一致
this.fileList.splice(index, 0, deletedFile);
this.$emit('change', this.fileList);
this.$emit('input', this.fileList);
uni.showToast({
title: '删除失败,请重试',
icon: 'none'
});
return;
}
this.replaceKnownFileIds(finalFileIds);
await this.referenceFiles({
explicitFileIds: finalFileIds,
source: 'delete'
});
} catch (error) {
console.error("删除后重新关联失败:", error);
this.fileList.splice(index, 0, deletedFile);
this.$emit('change', this.fileList);
this.$emit('input', this.fileList);
uni.showToast({
title: '删除失败,请重试',
icon: 'none'
});
}
},
/**
* 手动上传
*/
upload() {
if (this.$refs.uUploadRef && !this.disabled) {
this.$refs.uUploadRef.chooseFile();
}
},
/**
* 获取上传成功的文件
*/
getSuccessFiles() {
return this.fileList.filter(item => item.status === "success");
},
/**
* 清空文件
*/
clearFiles() {
this.fileList = [];
this.replaceKnownFileIds([]);
this.$emit('input', []);
this.$emit('change', []);
}
}
};
</script>
<style scoped>
::v-deep .u-upload__deletable {
width: 56rpx !important;
height: 56rpx !important;
top: -16rpx !important;
right: -16rpx !important;
background-color: transparent !important;
border-bottom-left-radius: 0 !important;
}
::v-deep .u-upload__deletable__icon {
position: absolute !important;
top: 10rpx !important;
right: 10rpx !important;
width: 24rpx;
height: 24rpx;
display: flex;
align-items: center;
justify-content: center;
background-color: rgb(55, 55, 55);
border-radius: 100rpx;
transform: none !important;
}
</style>