WMS_PDA/components/uploadImgCos/uploadImgCos.vue

686 lines
17 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()
};
},
computed: {
fileList: {
get() {
return this.internalFileList;
},
set(value) {
this.internalFileList = value;
}
}
},
watch: {
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)) || '';
},
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];
},
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
});
return this.extractImageListFromGetImagesResponse(response)
.map(item => ({
fileId: this.getRemoteFileId(item),
url: this.getRemoteFileUrl(item)
}))
.filter(item => item.fileId || item.url);
},
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) {
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)) || ''
);
if (!deletedUrl) {
return [];
}
try {
const remoteEntries = await this.getRemoteImageEntries();
const matched = remoteEntries
.filter(item => item.fileId && item.url && item.url === deletedUrl)
.map(item => item.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)
};
});
},
/**
* 提取文件名
*/
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();
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();
// 触发成功事件
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 = [] } = options;
console.log("this.fileList",this.fileList);
try {
// 获取所有成功的文件(包括之前已经关联的)
const localFileIds = this.fileList
.filter(item => item.status === "success" && this.getFileId(item))
.map(item => this.getFileId(item));
const remoteFileIds = mergeRemote ? await this.getRemoteFileIds() : [];
const excludedSet = new Set(
(Array.isArray(excludedFileIds) ? excludedFileIds : [excludedFileIds]).filter(Boolean)
);
const mergedFileIds = Array.from(new Set([...(remoteFileIds || []), ...(localFileIds || [])]))
.filter(fileId => !excludedSet.has(fileId));
const validFiles = mergedFileIds.map(fileId => ({ file_id: fileId }));
if (process.env.NODE_ENV !== 'production') {
console.log('[UploadImgCos] ReferenceFile payload debug', {
business_id: this.business_id,
type: this.business_type,
merge_remote: mergeRemote,
excluded_file_ids: Array.from(excludedSet),
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 response = await this.$http('common.ReferenceFile', {
id: this.business_id,
type: this.business_type,
images: []
});
// 更新外部绑定
this.$emit('change', this.fileList);
this.$emit('input', this.fileList);
return response;
}
const response = await this.$http('common.ReferenceFile', {
id: this.business_id,
type: this.business_type,
images: validFiles
});
// 更新外部绑定
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];
// 从列表中移除
this.fileList.splice(index, 1);
// 立即更新UI
this.$emit('delete', {
file: deletedFile,
index
});
// 更新外部绑定(立即更新,不等待)
this.$emit('change', this.fileList);
this.$emit('input', this.fileList);
// 异步更新文件关联:合并远端+本地,仅排除当前删除项,避免误删其他图片
try {
const deletedFileIds = await this.resolveDeletedFileIds(deletedFile);
await this.referenceFiles({
mergeRemote: true,
excludedFileIds: deletedFileIds
});
} 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>
::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>