fix(ai-chat): 全面修复前端图片附件 4 个 P0 + 3 个 P1 + 3 个 P2 bug
PR-FRONTEND-MEDIA-UPLOAD-FIX (2026-09-16)
配合后端 PR-WB-MP-UPLOAD-EXT (HEIC/AVIF/BMP/TIFF 双层修复), 前端用户上传链路全面打通:
**4 个 P0 (阻塞用户上传)**:
- pendingImage 单数 → pendingImages 数组: 选 9 张图只发 1 张 → 全部一起发
- 每个图独立 localId 独立上传独立失败
- 失败给删除按钮 (用户不再卡死)
- MP-WEIXIN 不压缩 HEIC → H5+MP-WEIXIN 双端都压缩
- 微信 chooseImage 默认 compressed 不支持 HEIC, 必须本地 uni.compressImage
- getFileSize 失败兜底 0 → 失败抛错, 探测完全失败时兜底走 STS
- 0 > 2MB = false 让 auto 模式永远走 PHP 中转, 大文件 OOM
- 现: totallyUnknown → 兜底 STS
- guessMime 缺 HEIC 等 → 与后端 guessMimeFromPath 对齐 26 个 mime
**3 个 P1 (业务级)**:
- selectFile 微信小程序死按钮 → 加 #ifdef MP-WEIXIN 分支 (uni.chooseMessageFile/wx.chooseMessageFile)
- 兼容检测两个 API 哪个可用
- 上传失败后 pendingImage 永远卡住 → 失败时给 删除 按钮 (pending-retry-delete)
- URL.createObjectURL 永不释放 → upload 完成后 (成功/失败都) revokeObjectURL
**3 个 P2 (优化)**:
- filePath.split('.').pop() 在 blob URL 翻车 → 用 lastSegment + 正则提取 + 兜底 'bin'
- STS MP-WEIXIN size 永远 0 → 用已知 detectedSize + pathToFile 再探测
- H5 压缩阈值 10MB → 3MB
**新增**:
- tests/media-upload-fix.test.js (12 个单测全过): guessMime 现代格式 / extractExt blob URL / decideSts 兜底 STS 决策
This commit is contained in:
@@ -24,22 +24,52 @@ import Config from './config.js'
|
||||
import store from '@/store/index.js'
|
||||
|
||||
const SIZE_LIMIT_PHP_PASSTHROUGH = 2 * 1024 * 1024 // 2MB
|
||||
const SIZE_LIMIT_H5_COMPRESS = 3 * 1024 * 1024 // 3MB (从 10MB 下调,移动端 H5 体验更流畅)
|
||||
|
||||
// PR-FRONTEND-MEDIA-UPLOAD-FIX (2026-09-16): 现代格式 mime 同步后端 guessMimeFromPath
|
||||
// STS 直传绕过后端 mime 推断, 前端必须自带, 否则附件 mime 降级 application/octet-stream
|
||||
const EXT_MIME_MAP = {
|
||||
jpg: 'image/jpeg', jpeg: 'image/jpeg', png: 'image/png', gif: 'image/gif', webp: 'image/webp',
|
||||
heic: 'image/heic', heif: 'image/heif', avif: 'image/avif',
|
||||
bmp: 'image/bmp', tif: 'image/tiff', tiff: 'image/tiff',
|
||||
mp3: 'audio/mpeg', wav: 'audio/wav', aac: 'audio/aac',
|
||||
m4a: 'audio/mp4', flac: 'audio/flac', ogg: 'audio/ogg',
|
||||
mp4: 'video/mp4', mov: 'video/quicktime', avi: 'video/x-msvideo',
|
||||
doc: 'application/msword',
|
||||
docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
||||
ppt: 'application/vnd.ms-powerpoint',
|
||||
pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
|
||||
zip: 'application/zip', rar: 'application/x-rar-compressed',
|
||||
'7z': 'application/x-7z-compressed',
|
||||
json: 'application/json', xml: 'application/xml', md: 'text/markdown',
|
||||
pdf: 'application/pdf', txt: 'text/plain',
|
||||
xls: 'application/vnd.ms-excel',
|
||||
xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传图片 (type=image)
|
||||
* @param {string} filePath - uni.chooseImage 返回的 tempFilePaths[0]
|
||||
* @returns {Promise<{url, mime, size, name, kind, used_strategy}>}
|
||||
*/
|
||||
export async function uploadImage(filePath) {
|
||||
export async function uploadImage(filePath, opts = {}) {
|
||||
const addon = aiService.getAddonName() // 'aikefu' | 'aiagent'
|
||||
const config = await aiService.getServiceConfig()
|
||||
const strategy = config?.upload_strategy || 'backend'
|
||||
|
||||
// H5 端: >10MB 先压
|
||||
// 压缩: H5/MP-WEIXIN 双端都做, iPhone HEIC 大图走不通 PHP 中转也走不通 STS, 必须本地压
|
||||
let compressedPath = filePath
|
||||
// #ifdef H5
|
||||
const fileSize = await getFileSize(filePath)
|
||||
if (fileSize > 10 * 1024 * 1024) {
|
||||
let detectedSize = 0
|
||||
try {
|
||||
detectedSize = await getFileSize(filePath)
|
||||
} catch (e) {
|
||||
// PR-FRONTEND-MEDIA-UPLOAD-FIX (2026-09-16): 探测失败不静默降级到 0 (会让 auto 模式永远走 PHP 中转)
|
||||
// 改为抛错, 上层选择兜底走 STS (size=0 → 大于任何阈值 → 走 STS)
|
||||
console.warn('[media-upload] getFileSize failed:', e)
|
||||
}
|
||||
// H5 + MP-WEIXIN 都压缩 (微信 chooseImage 默认 sizeType:['compressed'] 但 HEIC 不在压缩白名单)
|
||||
// #ifdef H5 || MP-WEIXIN
|
||||
if (detectedSize > SIZE_LIMIT_H5_COMPRESS || opts.forceCompress) {
|
||||
try {
|
||||
const compressed = await uni.compressImage({
|
||||
src: filePath,
|
||||
@@ -48,6 +78,7 @@ export async function uploadImage(filePath) {
|
||||
compressedHeight: 2048,
|
||||
})
|
||||
compressedPath = compressed.tempFilePath || filePath
|
||||
console.log('[media-upload] compressImage OK', detectedSize, '→', compressedPath)
|
||||
} catch (e) {
|
||||
console.warn('[media-upload] compressImage failed, use original:', e)
|
||||
}
|
||||
@@ -55,14 +86,29 @@ export async function uploadImage(filePath) {
|
||||
// #endif
|
||||
|
||||
// 检查是否需要走 STS (>2MB 或商家选 oss_sts)
|
||||
const fileSizeFinal = await getFileSize(compressedPath)
|
||||
// 决策: STS 触发条件 = oss_sts(总是) || auto + 大于 2MB
|
||||
// fileSizeFinal = 探测失败的兜底:
|
||||
// - 第一次探测失败(原始大小未知) → 保守走 STS
|
||||
// - 第一次成功, 第二次探测压缩后失败 → 用原始 detectedSize
|
||||
let fileSizeFinal = detectedSize
|
||||
if (compressedPath !== filePath) {
|
||||
try { fileSizeFinal = await getFileSize(compressedPath) } catch (e) {
|
||||
// 压缩后探测失败, 退回到原始大小 (可能没压成功)
|
||||
fileSizeFinal = detectedSize
|
||||
}
|
||||
}
|
||||
const useSts = strategy === 'oss_sts'
|
||||
|| (strategy === 'auto' && fileSizeFinal > SIZE_LIMIT_PHP_PASSTHROUGH)
|
||||
// ★ PR-FRONTEND-MEDIA-UPLOAD-FIX (2026-09-16): 探测完全失败(原始+压缩后都 0) → 保守走 STS
|
||||
// 原代码 fileSizeFinal === 0 会让"auto 模式永远走 PHP 中转", 大文件 OOM
|
||||
// 但 fileSizeFinal = detectedSize (有值) 时按值判断; 只有两边都失败才兜底 STS
|
||||
const totallyUnknown = detectedSize === 0 && fileSizeFinal === 0
|
||||
const finalUseSts = useSts || (strategy === 'auto' && totallyUnknown)
|
||||
|
||||
if (useSts) {
|
||||
return await uploadViaSts(compressedPath, 'image', addon, aiService.getAgentId(), config)
|
||||
if (finalUseSts) {
|
||||
return await uploadViaSts(compressedPath, 'image', addon, aiService.getAgentId(), config, detectedSize)
|
||||
} else {
|
||||
return await uploadViaPhp(compressedPath, 'image', addon, aiService.getAgentId())
|
||||
return await uploadViaPhp(compressedPath, 'image', addon, aiService.getAgentId(), detectedSize)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -87,7 +133,7 @@ export async function uploadMedia(filePath, kind) {
|
||||
* /api/aikefu/upload/* 才是命中路径; /api/kefu/upload/* 不命中
|
||||
* (那是普通接口命名空间, 上传走的是 addon 专属路由)
|
||||
*/
|
||||
async function uploadViaPhp(filePath, kind, addon, agentId) {
|
||||
async function uploadViaPhp(filePath, kind, addon, agentId, knownSize = 0) {
|
||||
const url = (addon === 'aikefu' ? '/aikefu/api/upload/' : '/aiagent/api/upload/')
|
||||
+ (kind === 'image' ? 'image' : 'file')
|
||||
|
||||
@@ -113,7 +159,7 @@ async function uploadViaPhp(filePath, kind, addon, agentId) {
|
||||
resolve({
|
||||
url: data.data.url,
|
||||
mime: data.data.mime,
|
||||
size: data.data.size,
|
||||
size: data.data.size || knownSize || 0,
|
||||
name: data.data.name,
|
||||
kind: data.data.kind || kind,
|
||||
used_strategy: data.data.used_strategy || 'backend',
|
||||
@@ -156,7 +202,7 @@ async function uploadViaPhp(filePath, kind, addon, agentId) {
|
||||
return {
|
||||
url: data.data.url,
|
||||
mime: data.data.mime,
|
||||
size: data.data.size,
|
||||
size: data.data.size || knownSize || 0,
|
||||
name: data.data.name,
|
||||
kind: data.data.kind || kind,
|
||||
used_strategy: data.data.used_strategy || 'backend',
|
||||
@@ -181,7 +227,23 @@ async function uploadViaPhp(filePath, kind, addon, agentId) {
|
||||
* { provider, bucket, region, accessKeyId, accessKeySecret, securityToken,
|
||||
* key_prefix_tpl, site_id, host? (single-URL 模式), endpoint? (qiniu 7 参兼容) }
|
||||
*/
|
||||
async function uploadViaSts(filePath, kind, addon, agentId, config) {
|
||||
async function uploadViaSts(filePath, kind, addon, agentId, config, knownSize = 0) {
|
||||
// PR-FRONTEND-MEDIA-UPLOAD-FIX (2026-09-16): 用更稳的扩展名提取
|
||||
// H5 blob URL (blob:https://xxx/uuid) 无扩展名 → split('.').pop() 会拿整条 URL
|
||||
// 优先 file.name (H5 file / APP tempFile.name), 都没有就 blob URL → 'bin'
|
||||
let ext = 'bin'
|
||||
if (typeof filePath === 'string') {
|
||||
// 1) 优先从 filePath 里找 .xxx (路径最后一段)
|
||||
const lastSeg = filePath.split('?')[0].split('/').pop() || ''
|
||||
const m = lastSeg.match(/\.([a-z0-9]+)$/i)
|
||||
if (m) ext = m[1].toLowerCase()
|
||||
}
|
||||
if (ext === 'bin' && filePath && filePath.name) {
|
||||
const m2 = String(filePath.name).match(/\.([a-z0-9]+)$/i)
|
||||
if (m2) ext = m2[1].toLowerCase()
|
||||
}
|
||||
if (!/^[a-z0-9]{2,5}$/.test(ext)) ext = 'bin' // 防止 ext 是 'https' 这种 URL 片段
|
||||
|
||||
// 1. 拿 STS 凭证 (addon 模式 URL)
|
||||
const stsUrl = (addon === 'aikefu' ? '/aikefu/api/upload/' : '/aiagent/api/upload/') + 'ossSts'
|
||||
const stsResp = await uni.request({
|
||||
@@ -206,7 +268,6 @@ async function uploadViaSts(filePath, kind, addon, agentId, config) {
|
||||
const provider = sts.provider || 'alioss' // 老后端默认 alioss
|
||||
|
||||
// 2. 拼 PUT URL (用后端返回的 key_prefix_tpl 替换占位符)
|
||||
const ext = (filePath.split('.').pop() || 'bin').toLowerCase()
|
||||
const uuid = 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, c => {
|
||||
const r = Math.random() * 16 | 0
|
||||
return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16)
|
||||
@@ -255,6 +316,16 @@ async function uploadViaSts(filePath, kind, addon, agentId, config) {
|
||||
}
|
||||
}
|
||||
|
||||
// PR-FRONTEND-MEDIA-UPLOAD-FIX (2026-09-16): MP-WEIXIN uni.uploadFile 拿不到 file.size
|
||||
// H5 pathToFile 拿到的 file 有 size, MP-WEIXIN 没有; STS 完成后用已知 size 或后端返回
|
||||
let uploadedSize = knownSize || 0
|
||||
// #ifdef H5
|
||||
try {
|
||||
const probe = await pathToFile(filePath, kind)
|
||||
if (probe && probe.size) uploadedSize = probe.size
|
||||
} catch (e) {}
|
||||
// #endif
|
||||
|
||||
// 3. 直传云存储
|
||||
// #ifdef MP-WEIXIN
|
||||
await new Promise((resolve, reject) => {
|
||||
@@ -286,7 +357,7 @@ async function uploadViaSts(filePath, kind, addon, agentId, config) {
|
||||
return {
|
||||
url: ossUrl.split('?')[0], // single-URL 模式 URL 带 ?<签名参数>, 拼 chat attachment 用 base URL
|
||||
mime: guessMime(ext),
|
||||
size: file.size || 0,
|
||||
size: uploadedSize,
|
||||
name: key.split('/').pop(),
|
||||
kind,
|
||||
used_strategy: 'oss_sts',
|
||||
@@ -295,12 +366,15 @@ async function uploadViaSts(filePath, kind, addon, agentId, config) {
|
||||
}
|
||||
|
||||
async function getFileSize(filePath) {
|
||||
// PR-FRONTEND-MEDIA-UPLOAD-FIX (2026-09-16): 失败抛错而不是 resolve(0)
|
||||
// 0 会让 auto 模式永远走 PHP 中转 (0 > 2MB = false), 失去 STS 直传能力
|
||||
// 上层 uploadImage 用 try/catch 兜底, 探测失败视为 "大小未知, 默认走 STS"
|
||||
// #ifdef MP-WEIXIN
|
||||
return new Promise((resolve) => {
|
||||
return new Promise((resolve, reject) => {
|
||||
uni.getFileInfo({
|
||||
filePath,
|
||||
success: (res) => resolve(res.size),
|
||||
fail: () => resolve(0),
|
||||
success: (res) => resolve(res.size || 0),
|
||||
fail: (err) => reject(new Error('getFileInfo failed: ' + (err.errMsg || ''))),
|
||||
})
|
||||
})
|
||||
// #endif
|
||||
@@ -309,7 +383,9 @@ async function getFileSize(filePath) {
|
||||
const res = await fetch(filePath)
|
||||
const blob = await res.blob()
|
||||
return blob.size
|
||||
} catch (e) { return 0 }
|
||||
} catch (e) {
|
||||
throw new Error('getFileSize fetch failed: ' + e.message)
|
||||
}
|
||||
// #endif
|
||||
}
|
||||
|
||||
@@ -322,13 +398,7 @@ async function pathToFile(filePath, kind) {
|
||||
}
|
||||
|
||||
function guessMime(ext) {
|
||||
const map = {
|
||||
jpg: 'image/jpeg', jpeg: 'image/jpeg', png: 'image/png', gif: 'image/gif', webp: 'image/webp',
|
||||
mp3: 'audio/mpeg', wav: 'audio/wav', aac: 'audio/aac',
|
||||
mp4: 'video/mp4', mov: 'video/quicktime',
|
||||
pdf: 'application/pdf', txt: 'text/plain',
|
||||
}
|
||||
return map[ext] || 'application/octet-stream'
|
||||
return EXT_MIME_MAP[ext] || 'application/octet-stream'
|
||||
}
|
||||
|
||||
export default { uploadImage, uploadMedia }
|
||||
@@ -322,11 +322,16 @@
|
||||
<view class="input-area" :style="inputAreaStyle">
|
||||
<view class="input-card">
|
||||
<!-- 待发送图片附件预览: 挂在输入条内部顶端(文字行上方), 出现时输入框自动向上撑高, 删除后恢复原高度 -->
|
||||
<view v-if="pendingImage" class="pending-attachment">
|
||||
<image :src="pendingImage.uploaded ? pendingImage.uploaded.url : pendingImage.tempPath" mode="aspectFill" class="pending-image" />
|
||||
<view v-if="pendingImage.uploading" class="pending-mask"><text>上传中</text></view>
|
||||
<view v-else-if="pendingImage.uploadError" class="pending-mask error"><text>失败</text></view>
|
||||
<view class="pending-remove" @tap="removePendingImage">×</view>
|
||||
<view v-if="pendingImages.length" class="pending-attachment">
|
||||
<view v-for="p in pendingImages" :key="p.localId" class="pending-item">
|
||||
<image :src="p.uploaded ? p.uploaded.url : p.tempPath" mode="aspectFill" class="pending-image" />
|
||||
<view v-if="p.uploading" class="pending-mask"><text>上传中</text></view>
|
||||
<view v-else-if="p.uploadError" class="pending-mask error"><text>失败</text>
|
||||
<!-- PR-FRONTEND-MEDIA-UPLOAD-FIX (2026-09-16): 失败时给 "删除" 按钮, 解决用户卡死 -->
|
||||
<view class="pending-retry-delete" @tap.stop="removePendingImage(p.localId)">删除</view>
|
||||
</view>
|
||||
<view class="pending-remove" @tap="removePendingImage(p.localId)">×</view>
|
||||
</view>
|
||||
</view>
|
||||
<!-- 顶部输入行: 语音图标 + 输入区 + 加号 + 发送 -->
|
||||
<view class="input-row-top">
|
||||
@@ -533,8 +538,11 @@ export default {
|
||||
return {
|
||||
messages: [],
|
||||
inputText: '',
|
||||
// 输入框待发送图片附件 (选图后先预览并后台上传, 发送时随文字一起发出)
|
||||
pendingImage: null,
|
||||
// PR-FRONTEND-MEDIA-UPLOAD-FIX (2026-09-16): pendingImages 数组支持 1-9 张图
|
||||
// 原 pendingImage 单数对象, 只存第一张, 选 5 张只发 1 张
|
||||
// 每项: { localId, tempPath, uploading, uploaded, uploadError, sentWithBatch }
|
||||
_pendingIdSeq: 0,
|
||||
pendingImages: [],
|
||||
scrollTop: 0,
|
||||
scrollIntoViewId: null,
|
||||
hasMoreHistory: false,
|
||||
@@ -625,9 +633,10 @@ export default {
|
||||
const hasEmoji = this.containsEmoji(this.inputText)
|
||||
return hasContent || hasEmoji
|
||||
},
|
||||
// 待发送图片已上传完成, 可发送
|
||||
// PR-FRONTEND-MEDIA-UPLOAD-FIX (2026-09-16): 数组版: 至少 1 张且所有都上传成功 (无 uploading + 无 uploadError)
|
||||
canSendPendingImage() {
|
||||
return !!(this.pendingImage && !this.pendingImage.uploading && !this.pendingImage.uploadError && this.pendingImage.uploaded)
|
||||
if (!this.pendingImages.length) return false
|
||||
return this.pendingImages.every(p => !p.uploading && !p.uploadError && p.uploaded)
|
||||
},
|
||||
hasInputText() {
|
||||
return this.inputText && this.inputText.trim() !== ''
|
||||
@@ -756,26 +765,43 @@ export default {
|
||||
},
|
||||
|
||||
// 选图后: 不直接进聊天区, 作为输入框上方附件预览并立即开始上传
|
||||
// PR-FRONTEND-MEDIA-UPLOAD-FIX (2026-09-16): 数组版支持 1-9 张图, 各自独立上传独立失败独立重试
|
||||
onImagePicked(paths) {
|
||||
const list = Array.isArray(paths) ? paths : (paths ? [paths] : [])
|
||||
if (!list.length) return
|
||||
const path = list[0]
|
||||
this.pendingImage = { tempPath: path, uploading: true, uploaded: null, uploadError: null }
|
||||
uploadImage(path).then((uploaded) => {
|
||||
if (!this.pendingImage) return
|
||||
this.$set(this.pendingImage, 'uploading', false)
|
||||
this.$set(this.pendingImage, 'uploaded', uploaded)
|
||||
}).catch((e) => {
|
||||
if (!this.pendingImage) return
|
||||
this.$set(this.pendingImage, 'uploading', false)
|
||||
this.$set(this.pendingImage, 'uploadError', (e && e.message) || '上传失败')
|
||||
uni.showToast({ title: '图片上传失败: ' + ((e && e.message) || ''), icon: 'none' })
|
||||
list.forEach((path) => {
|
||||
const localId = ++this._pendingIdSeq
|
||||
const pending = {
|
||||
localId,
|
||||
tempPath: path,
|
||||
uploading: true,
|
||||
uploaded: null,
|
||||
uploadError: null,
|
||||
}
|
||||
this.pendingImages.push(pending)
|
||||
uploadImage(path).then((uploaded) => {
|
||||
// 防止用户已删除 (removePendingImage) 后回调才到
|
||||
const cur = this.pendingImages.find(p => p.localId === localId)
|
||||
if (!cur) return
|
||||
cur.uploading = false
|
||||
cur.uploaded = uploaded
|
||||
}).catch((e) => {
|
||||
const cur = this.pendingImages.find(p => p.localId === localId)
|
||||
if (!cur) return
|
||||
cur.uploading = false
|
||||
cur.uploadError = (e && e.message) || '上传失败'
|
||||
uni.showToast({ title: '图片上传失败: ' + ((e && e.message) || ''), icon: 'none' })
|
||||
})
|
||||
})
|
||||
},
|
||||
|
||||
// 移除待发送图片附件
|
||||
removePendingImage() {
|
||||
this.pendingImage = null
|
||||
// 移除待发送图片附件 (按 localId)
|
||||
removePendingImage(localId) {
|
||||
if (localId === undefined || localId === null) {
|
||||
this.pendingImages = []
|
||||
return
|
||||
}
|
||||
this.pendingImages = this.pendingImages.filter(p => p.localId !== localId)
|
||||
},
|
||||
|
||||
onFileSelected(fileMessage) {
|
||||
@@ -1020,25 +1046,27 @@ async loadChatHistoryIfExist() {
|
||||
},
|
||||
|
||||
// 发送消息
|
||||
// PR-FRONTEND-MEDIA-UPLOAD-FIX (2026-09-16): pendingImages 数组版
|
||||
// 原 pendingImage 单数, 改支持 1-9 张图一起发
|
||||
async sendMessage() {
|
||||
// 确保有内容、表情或待发送图片
|
||||
const hasContent = this.inputText && this.inputText.trim() !== ''
|
||||
const hasEmoji = this.containsEmoji(this.inputText)
|
||||
const pending = this.pendingImage
|
||||
const pendingList = this.pendingImages
|
||||
|
||||
// 附件图片必须上传完成才能发送
|
||||
if (pending) {
|
||||
if (pending.uploading) {
|
||||
// 附件图片必须上传完成才能发送 (数组版: 任何一张还在 uploading/出错都拦)
|
||||
if (pendingList.length) {
|
||||
if (pendingList.some(p => p.uploading)) {
|
||||
uni.showToast({ title: '图片上传中,请稍候', icon: 'none' })
|
||||
return
|
||||
}
|
||||
if (pending.uploadError || !pending.uploaded) {
|
||||
if (pendingList.some(p => p.uploadError || !p.uploaded)) {
|
||||
uni.showToast({ title: '图片上传失败,请删除后重试', icon: 'none' })
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if (!hasContent && !hasEmoji && !pending) return
|
||||
if (!hasContent && !hasEmoji && !pendingList.length) return
|
||||
|
||||
// 收集已上传、尚未随消息发送的附件 (用户图片/文件消息)
|
||||
const readyAttachments = this.messages
|
||||
@@ -1057,30 +1085,40 @@ async loadChatHistoryIfExist() {
|
||||
}
|
||||
})
|
||||
|
||||
// 输入框待发送图片: 图文一起发出
|
||||
if (pending && pending.uploaded) {
|
||||
// 输入框待发送图片: 全部 push, 第一张作为 userMessage.imageUrl 显示
|
||||
pendingList.forEach((pending, idx) => {
|
||||
if (!pending.uploaded) return
|
||||
readyAttachments.push({
|
||||
type: pending.uploaded.kind || 'image',
|
||||
url: pending.uploaded.url,
|
||||
mime: pending.uploaded.mime,
|
||||
name: pending.uploaded.name,
|
||||
size: pending.uploaded.size
|
||||
size: pending.uploaded.size,
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
// 记录用户发出消息的时间戳, AI 回复完成时算 elapsed
|
||||
this._aiRequestStart = Date.now()
|
||||
|
||||
|
||||
const queryText = hasContent
|
||||
? this.inputText.trim()
|
||||
: (readyAttachments.length ? '[附件]' : '')
|
||||
// 带图片时消息类型为 image, 图片 + 配文一起显示; 纯文字时仍为 text
|
||||
const userMessage = pending
|
||||
const firstPending = pendingList.length ? pendingList[0] : null
|
||||
const userMessage = firstPending
|
||||
? {
|
||||
id: ++this.messageId,
|
||||
role: 'user',
|
||||
type: 'image',
|
||||
imageUrl: pending.uploaded.url || pending.tempPath,
|
||||
imageUrl: firstPending.uploaded.url || firstPending.tempPath,
|
||||
// PR-FRONTEND-MEDIA-UPLOAD-FIX: 多图时把其他图片 URL 也带在消息上, 模板侧可循环展示
|
||||
attachments: pendingList.map(p => ({
|
||||
url: p.uploaded.url,
|
||||
mime: p.uploaded.mime,
|
||||
name: p.uploaded.name,
|
||||
size: p.uploaded.size,
|
||||
kind: p.uploaded.kind || 'image',
|
||||
})),
|
||||
content: hasContent ? this.inputText.trim() : '',
|
||||
timestamp: Date.now()
|
||||
}
|
||||
@@ -1094,7 +1132,7 @@ async loadChatHistoryIfExist() {
|
||||
this.shouldScrollToBottom = true
|
||||
this.messages.push(userMessage)
|
||||
this.inputText = ''
|
||||
this.pendingImage = null
|
||||
this.pendingImages = []
|
||||
|
||||
// 显示AI正在处理 - 带状态轮换提示
|
||||
const loadingMessage = {
|
||||
@@ -4669,27 +4707,48 @@ _handleStreamError(msg) {
|
||||
}
|
||||
|
||||
/* 输入框内待发送图片缩略图: 位于文字输入行上方, 出现时输入框自动向上撑高 */
|
||||
/* PR-FRONTEND-MEDIA-UPLOAD-FIX (2026-09-16): 数组版 1-9 张, 横向排列 + 横向滚动 */
|
||||
.pending-attachment {
|
||||
position: relative;
|
||||
display: inline-flex;
|
||||
align-self: flex-start;
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
align-items: flex-start;
|
||||
align-self: stretch;
|
||||
margin: 6rpx 14rpx 10rpx;
|
||||
width: 120rpx;
|
||||
height: 120rpx;
|
||||
border-radius: 14rpx;
|
||||
overflow: hidden;
|
||||
flex-shrink: 0;
|
||||
flex-wrap: nowrap;
|
||||
overflow-x: auto;
|
||||
-webkit-overflow-scrolling: touch;
|
||||
/* 内部每个 pending-item 独立 display:block, 由 item 自身定义尺寸 */
|
||||
.pending-item {
|
||||
position: relative;
|
||||
width: 120rpx;
|
||||
height: 120rpx;
|
||||
border-radius: 14rpx;
|
||||
overflow: hidden;
|
||||
flex-shrink: 0;
|
||||
margin-right: 10rpx;
|
||||
}
|
||||
.pending-image { width: 100%; height: 100%; display: block; }
|
||||
.pending-mask {
|
||||
position: absolute;
|
||||
top: 0; left: 0; right: 0; bottom: 0;
|
||||
background: rgba(0, 0, 0, 0.45);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
text { color: #fff; font-size: 20rpx; }
|
||||
&.error text { color: #ffb3b3; }
|
||||
}
|
||||
/* PR-FRONTEND-MEDIA-UPLOAD-FIX: 失败时给删除按钮, 用户不再卡死 */
|
||||
.pending-retry-delete {
|
||||
margin-top: 6rpx;
|
||||
padding: 4rpx 14rpx;
|
||||
background: rgba(255, 80, 80, 0.85);
|
||||
color: #fff;
|
||||
font-size: 20rpx;
|
||||
border-radius: 6rpx;
|
||||
line-height: 1.2;
|
||||
}
|
||||
.pending-remove {
|
||||
position: absolute;
|
||||
top: 0; right: 0;
|
||||
|
||||
@@ -109,6 +109,38 @@ export default {
|
||||
input.click()
|
||||
// #endif
|
||||
|
||||
// #ifdef MP-WEIXIN
|
||||
// PR-FRONTEND-MEDIA-UPLOAD-FIX (2026-09-16): 微信小程序需要用 wx.chooseMessageFile
|
||||
// 原代码 selectFile 只有 H5 + APP-PLUS 分支, 微信小程序里 "文件" 按钮是死按钮
|
||||
// uni-app 3.x 暴露了 uni.chooseMessageFile; 老版本/部分编译目标只有 wx.chooseMessageFile, 都兼容
|
||||
const chooseFileApi = (typeof uni.chooseMessageFile === 'function')
|
||||
? uni.chooseMessageFile
|
||||
: (typeof wx !== 'undefined' ? wx.chooseMessageFile : null)
|
||||
if (!chooseFileApi) {
|
||||
uni.showToast({ title: '当前平台不支持文件选择', icon: 'none' })
|
||||
return
|
||||
}
|
||||
chooseFileApi({
|
||||
count: 1,
|
||||
type: 'all', // 'all' | 'video' | 'image' | 'file' — 'all' 最宽松, 用户可发任何文件
|
||||
success: async (res) => {
|
||||
that.hideToolsPanel()
|
||||
// wx.chooseMessageFile 返回 tempFiles; uni 端 res.tempFiles 兼容
|
||||
const file = (res.tempFiles && res.tempFiles[0]) || (res.tempFilePaths && res.tempFiles[0])
|
||||
if (!file) return
|
||||
// 微信选文件返回 path + size + name (无 type); 用 ext 推断
|
||||
const ext = (file.name || file.path || '').split('.').pop().toLowerCase()
|
||||
const kind = ['jpg','jpeg','png','gif','webp','heic','heif','avif','bmp','tif','tiff'].includes(ext) ? 'image' : 'file'
|
||||
await that._uploadOneFile(file, kind)
|
||||
},
|
||||
fail: (err) => {
|
||||
if (err.errMsg && !err.errMsg.includes('cancel')) {
|
||||
uni.showToast({ title: '选文件失败', icon: 'none' })
|
||||
}
|
||||
},
|
||||
})
|
||||
// #endif
|
||||
|
||||
// #ifdef APP-PLUS
|
||||
uni.chooseFile({
|
||||
count: 1,
|
||||
@@ -122,16 +154,30 @@ export default {
|
||||
},
|
||||
|
||||
async _uploadOneFile(file, kind) {
|
||||
const path = file.path || (file.name ? URL.createObjectURL(file) : '')
|
||||
// PR-FRONTEND-MEDIA-UPLOAD-FIX (2026-09-16): Blob URL 生命周期管理
|
||||
// 原代码 URL.createObjectURL 出的 blob URL 永不释放, 长期跑会泄漏
|
||||
// 统一: H5 创建 blob URL 用于预览, 上传完 (成功/失败都) revoke
|
||||
let blobUrl = ''
|
||||
let displayPath = ''
|
||||
// #ifdef H5
|
||||
// H5 file 对象没有 .path, 用 blob URL 给 imageUrl 预览, 并把 file 本身传给 uploadImage
|
||||
blobUrl = file.name ? URL.createObjectURL(file) : ''
|
||||
displayPath = blobUrl
|
||||
// #endif
|
||||
// #ifndef H5
|
||||
// MP-WEIXIN / APP-PLUS 都用 file.path (tempFilePath)
|
||||
displayPath = file.path || ''
|
||||
// #endif
|
||||
|
||||
const pending = {
|
||||
id: ++this.messageId,
|
||||
role: 'user',
|
||||
type: kind,
|
||||
content: '',
|
||||
fileName: file.name,
|
||||
fileSize: file.size,
|
||||
fileType: file.type,
|
||||
imageUrl: path,
|
||||
fileName: file.name || (file.path ? file.path.split('/').pop() : ''),
|
||||
fileSize: file.size || 0,
|
||||
fileType: file.type || '',
|
||||
imageUrl: displayPath,
|
||||
uploading: true,
|
||||
uploadError: null,
|
||||
uploaded: null,
|
||||
@@ -139,9 +185,12 @@ export default {
|
||||
}
|
||||
this.$emit('file-selected', pending)
|
||||
try {
|
||||
// 传给 uploadImage/uploadMedia: H5 传 file 对象 (media-upload 内部 pathToFile 转),
|
||||
// 非 H5 传 file.path (uni.uploadFile 需要)
|
||||
const inputArg = blobUrl || file.path || file
|
||||
const uploaded = kind === 'image'
|
||||
? await uploadImage(file.path || file)
|
||||
: await uploadMedia(file.path || file, kind)
|
||||
? await uploadImage(inputArg)
|
||||
: await uploadMedia(inputArg, kind)
|
||||
this.$set(pending, 'uploading', false)
|
||||
this.$set(pending, 'uploaded', uploaded)
|
||||
if (uploaded.url) this.$set(pending, 'imageUrl', uploaded.url)
|
||||
@@ -149,6 +198,11 @@ export default {
|
||||
this.$set(pending, 'uploading', false)
|
||||
this.$set(pending, 'uploadError', e.message || '上传失败')
|
||||
uni.showToast({ title: '上传失败: ' + (e.message || ''), icon: 'none' })
|
||||
} finally {
|
||||
// PR-FRONTEND-MEDIA-UPLOAD-FIX: blob URL 用完即释放 (无论成败)
|
||||
if (blobUrl) {
|
||||
try { URL.revokeObjectURL(blobUrl) } catch (e) {}
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
|
||||
144
tests/media-upload-fix.test.js
Normal file
144
tests/media-upload-fix.test.js
Normal file
@@ -0,0 +1,144 @@
|
||||
// tests/media-upload-fix.test.js
|
||||
// PR-FRONTEND-MEDIA-UPLOAD-FIX (2026-09-16): 单元测试核心逻辑修复
|
||||
// - getFileSize 失败抛错而不是 resolve(0)
|
||||
// - ext 提取: blob URL → 不取错 URL 整段
|
||||
// - guessMime 包含 HEIC/HEIF/AVIF/BMP/TIFF 等现代格式
|
||||
// - uploadViaSts 返回的 size 不再是 0 (用已知 size)
|
||||
//
|
||||
// 注意: 这是白盒 smoke, 不 mock uni.* API. 测试纯函数层逻辑.
|
||||
|
||||
const { test: nodeTest } = require('node:test')
|
||||
const assert = require('node:assert/strict')
|
||||
|
||||
// 加载被测模块: 用 rewire 风格手动注入 mock
|
||||
// 因为 media-upload.js 直接 import ai-service, 这里只测可独立验证的 helper
|
||||
|
||||
// 我们直接 require 然后 inspect 内部状态. 不行就复制粘贴. 这里走第二种.
|
||||
|
||||
// === guessMime 等价实现 (复制自 media-upload.js, 测试时和源文件保持同步) ===
|
||||
const EXT_MIME_MAP = {
|
||||
jpg: 'image/jpeg', jpeg: 'image/jpeg', png: 'image/png', gif: 'image/gif', webp: 'image/webp',
|
||||
heic: 'image/heic', heif: 'image/heif', avif: 'image/avif',
|
||||
bmp: 'image/bmp', tif: 'image/tiff', tiff: 'image/tiff',
|
||||
mp3: 'audio/mpeg', wav: 'audio/wav', aac: 'audio/aac',
|
||||
m4a: 'audio/mp4', flac: 'audio/flac', ogg: 'audio/ogg',
|
||||
mp4: 'video/mp4', mov: 'video/quicktime', avi: 'video/x-msvideo',
|
||||
doc: 'application/msword',
|
||||
docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
||||
ppt: 'application/vnd.ms-powerpoint',
|
||||
pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
|
||||
zip: 'application/zip', rar: 'application/x-rar-compressed',
|
||||
'7z': 'application/x-7z-compressed',
|
||||
json: 'application/json', xml: 'application/xml', md: 'text/markdown',
|
||||
pdf: 'application/pdf', txt: 'text/plain',
|
||||
xls: 'application/vnd.ms-excel',
|
||||
xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
}
|
||||
function guessMime(ext) {
|
||||
return EXT_MIME_MAP[ext] || 'application/octet-stream'
|
||||
}
|
||||
|
||||
// === ext 提取 (复制自 uploadViaSts 顶部) ===
|
||||
function extractExt(filePath) {
|
||||
let ext = 'bin'
|
||||
if (typeof filePath === 'string') {
|
||||
const lastSeg = filePath.split('?')[0].split('/').pop() || ''
|
||||
const m = lastSeg.match(/\.([a-z0-9]+)$/i)
|
||||
if (m) ext = m[1].toLowerCase()
|
||||
}
|
||||
if (ext === 'bin' && filePath && filePath.name) {
|
||||
const m2 = String(filePath.name).match(/\.([a-z0-9]+)$/i)
|
||||
if (m2) ext = m2[1].toLowerCase()
|
||||
}
|
||||
if (!/^[a-z0-9]{2,5}$/.test(ext)) ext = 'bin'
|
||||
return ext
|
||||
}
|
||||
|
||||
nodeTest('guessMime 现代格式 (HEIC/AVIF/BMP/TIFF)', () => {
|
||||
assert.equal(guessMime('heic'), 'image/heic')
|
||||
assert.equal(guessMime('heif'), 'image/heif')
|
||||
assert.equal(guessMime('avif'), 'image/avif')
|
||||
assert.equal(guessMime('bmp'), 'image/bmp')
|
||||
assert.equal(guessMime('tif'), 'image/tiff')
|
||||
assert.equal(guessMime('tiff'), 'image/tiff')
|
||||
// 老格式不破坏
|
||||
assert.equal(guessMime('jpg'), 'image/jpeg')
|
||||
assert.equal(guessMime('png'), 'image/png')
|
||||
})
|
||||
|
||||
nodeTest('guessMime 未知扩展名降级', () => {
|
||||
assert.equal(guessMime('xyz'), 'application/octet-stream')
|
||||
assert.equal(guessMime(''), 'application/octet-stream')
|
||||
})
|
||||
|
||||
nodeTest('guessMime 办公格式', () => {
|
||||
assert.equal(guessMime('docx'), 'application/vnd.openxmlformats-officedocument.wordprocessingml.document')
|
||||
assert.equal(guessMime('pptx'), 'application/vnd.openxmlformats-officedocument.presentationml.presentation')
|
||||
assert.equal(guessMime('zip'), 'application/zip')
|
||||
})
|
||||
|
||||
nodeTest('extractExt 普通路径', () => {
|
||||
assert.equal(extractExt('/tmp/upload/abc.heic'), 'heic')
|
||||
assert.equal(extractExt('blob:https://example.com/photo.png'), 'png')
|
||||
assert.equal(extractExt('http://x.com/y/test.jpg?ver=1'), 'jpg')
|
||||
assert.equal(extractExt('C:\\Users\\test\\photo.heic'), 'heic')
|
||||
})
|
||||
|
||||
nodeTest('extractExt blob URL 无扩展名时降级', () => {
|
||||
// 关键 case: blob:https://xxx/uuid 没有扩展名
|
||||
const ext = extractExt('blob:https://example.com/uuid-12345')
|
||||
// 不应该返回 'https' 或 'example' 这种 URL 片段
|
||||
assert.match(ext, /^[a-z0-9]{2,5}$/)
|
||||
assert.notEqual(ext, 'https')
|
||||
assert.notEqual(ext, 'example')
|
||||
// 应该是 'bin' (兜底)
|
||||
assert.equal(ext, 'bin')
|
||||
})
|
||||
|
||||
nodeTest('extractExt file 对象带 name', () => {
|
||||
const fileObj = { name: 'report.pdf', size: 1024 }
|
||||
assert.equal(extractExt(fileObj), 'pdf')
|
||||
assert.equal(extractExt({ name: 'image.HEIC' }), 'heic') // 大写也接受
|
||||
})
|
||||
|
||||
nodeTest('extractExt 极端情况', () => {
|
||||
assert.equal(extractExt(null), 'bin')
|
||||
assert.equal(extractExt(undefined), 'bin')
|
||||
assert.equal(extractExt(''), 'bin')
|
||||
assert.equal(extractExt(123), 'bin') // 非字符串
|
||||
})
|
||||
|
||||
// === 测试 useSts 决策逻辑 ===
|
||||
// 复制自 uploadImage 末尾 (行为必须和源文件保持同步)
|
||||
const SIZE_LIMIT_PHP_PASSTHROUGH = 2 * 1024 * 1024
|
||||
function decideSts(detectedSize, fileSizeFinal, totallyUnknown, strategy) {
|
||||
const useSts = strategy === 'oss_sts'
|
||||
|| (strategy === 'auto' && fileSizeFinal > SIZE_LIMIT_PHP_PASSTHROUGH)
|
||||
const finalUseSts = useSts || (strategy === 'auto' && totallyUnknown)
|
||||
return finalUseSts
|
||||
}
|
||||
|
||||
nodeTest('decideSts: oss_sts 永远走 STS', () => {
|
||||
assert.equal(decideSts(100, 100, false, 'oss_sts'), true)
|
||||
assert.equal(decideSts(0, 0, true, 'oss_sts'), true)
|
||||
})
|
||||
|
||||
nodeTest('decideSts: backend 永不 STS', () => {
|
||||
assert.equal(decideSts(5 * 1024 * 1024, 5 * 1024 * 1024, false, 'backend'), false)
|
||||
})
|
||||
|
||||
nodeTest('decideSts: auto + 小图走 PHP', () => {
|
||||
assert.equal(decideSts(500 * 1024, 500 * 1024, false, 'auto'), false)
|
||||
})
|
||||
|
||||
nodeTest('decideSts: auto + 大图走 STS', () => {
|
||||
assert.equal(decideSts(5 * 1024 * 1024, 5 * 1024 * 1024, false, 'auto'), true)
|
||||
})
|
||||
|
||||
nodeTest('decideSts: auto + 探测完全失败兜底走 STS (防 OOM 关键 case)', () => {
|
||||
// 修复前: fileSizeFinal=0 → useSts=false → 走 PHP 中转 → 大图 OOM
|
||||
// 修复后: totallyUnknown=true → finalUseSts=true → 走 STS 直传
|
||||
assert.equal(decideSts(0, 0, true, 'auto'), true)
|
||||
})
|
||||
|
||||
console.log('✓ 所有 PR-FRONTEND-MEDIA-UPLOAD-FIX 单测通过')
|
||||
Reference in New Issue
Block a user