This commit is contained in:
2025-09-04 21:21:53 +08:00
parent 19b6251011
commit 3ca2451b2f

View File

@@ -38,326 +38,293 @@
</template> </template>
<script> <script>
import { import { addRecord } from "@/api/inspection/record.js"
addRecord import { addWatermarkToImage } from "@/utils/watermark.js"
} from "@/api/inspection/record.js" import appConfig from "@/config"
// 如果你已有 uploadImg 封装且内部就是 uni.uploadFile可以继续用
// 但前提是它支持 H5 直接传 File 对象(不是 URL 字符串)。 // ------- URL 安全拼接,避免出现 /undefined/common/upload -------
// 这里我示范“直接用 uni.uploadFile”的写法更稳妥。 function joinURL(base, path) {
import { const b = (base || "").replace(/\/+$/, "")
addWatermarkToImage const p = (path || "").replace(/^\/+/, "")
} from "@/utils/watermark.js" return `${b}/${p}`
import appConfig from '@/config' }
const UPLOAD_URL = appConfig.baseUrl + "/common/upload" // 按你后端改 const BASE_URL = appConfig?.baseUrl || (process.env.VUE_APP_BASE_API || "")
const UPLOAD_URL = joinURL(BASE_URL, "/common/upload")
export default { export default {
data() { data() {
return { return {
form: { form: {
inspectionType: 0, inspectionType: 0,
inspectorId: this.$store.state.user.nickName, inspectorId: this.$store.state.user.nickName,
inspectionPoint: "", inspectionPoint: "",
inspectionRequirements: "", inspectionRequirements: "",
inspectionImg: "", inspectionImg: "",
ImgUrl: [], // 后端返回的文件名/URL ImgUrl: [], // 后端返回的文件名/URL
remark: "" remark: ""
}, },
img: [], // 绑定给 uni-file-picker 预览列表 img: [], // uni-file-picker 预览
sourceType: ['camera'], sourceType: ["camera"],
msgType: '', msgType: "",
messageText: '', messageText: "",
isUploading: false, isUploading: false,
isMobileBrowser: false isMobileBrowser: false
} }
}, },
methods: { methods: {
async submit() { async submit() {
if (this.isUploading) { if (this.isUploading) {
this.showMessage('warning', '图片正在上传中,请稍等') this.showMessage("warning", "图片正在上传中,请稍等")
return return
} }
if (!Array.isArray(this.form.ImgUrl) || this.form.ImgUrl.length === 0) { if (!Array.isArray(this.form.ImgUrl) || this.form.ImgUrl.length === 0) {
this.showMessage('error', '请选择要上传的图片') this.showMessage("error", "请选择要上传的图片")
return return
} }
this.form.inspectionImg = this.joinList() this.form.inspectionImg = this.joinList()
try { try {
const res = await addRecord(this.form) const res = await addRecord(this.form)
if (res.code === 200) { if (res.code === 200) {
this.showMessage('success', '打卡成功') this.showMessage("success", "打卡成功")
} else { } else {
this.showMessage('error', '打卡失败') this.showMessage("error", res.msg || "打卡失败")
} }
} catch (err) { } catch (err) {
this.showMessage('error', `提交失败: ${err.message}`) this.showMessage("error", `提交失败: ${err.message}`)
} }
}, },
// uni-file-picker 删除e.tempFile 里通常有 {url/path},与你传给 value 的结构需一致 // 删除预览 & 同步删除结果
deleteImg(e) { deleteImg(e) {
const url = e.tempFile?.url || e.tempFile?.path const url = e?.tempFile?.url || e?.tempFile?.path
const idx = this.img.findIndex(x => x.url === url) const idx = this.img.findIndex((x) => x.url === url)
if (idx !== -1) { if (idx !== -1) {
this.img.splice(idx, 1) // 释放预览 URL 内存
// 同步移除已上传结果(按你的业务,可以用同索引移除或按返回名移除) try {
this.form.ImgUrl.splice(idx, 1) const toRevoke = this.img[idx]?.url
} toRevoke && toRevoke.startsWith("blob:") && URL.revokeObjectURL(toRevoke)
}, } catch {}
this.img.splice(idx, 1)
this.form.ImgUrl.splice(idx, 1)
}
},
// 选择文件(支持多张) // 选择文件(支持多张)
async upload(e) { async upload(e) {
if (!e?.tempFiles?.length) return if (!e?.tempFiles?.length) return
if (this.isUploading) { if (this.isUploading) {
this.showMessage('warning', '图片正在上传中,请稍等') this.showMessage("warning", "图片正在上传中,请稍等")
return return
} }
this.isUploading = true this.isUploading = true
try { try {
// 逐张处理 for (const tf of e.tempFiles) {
for (const tf of e.tempFiles) { await this.handleImageUpload(tf)
await this.handleImageUpload(tf) // 这里传入每个 tempFile }
} } catch (err) {
// this.showMessage('success', '图片处理/上传完成') console.error(err)
} catch (err) { this.showMessage("error", `图片上传失败:${err.message || err}`)
console.error(err) } finally {
this.showMessage('error', `图片上传失败:${err.message || err}`) this.isUploading = false
} finally { }
this.isUploading = false },
}
},
// 单张处理:加水印 ->(可选)压缩 -> 上传 // 单张:加水印 -> 压缩(H5) -> 预览 -> 上传
async handleImageUpload(tempFile) { async handleImageUpload(tempFile) {
// tempFile.file: H5 下是 File 对象App/小程序是临时路径 // H5uni-file-picker 的 e.tempFiles[i].file 就是 File
const raw = tempFile.file || tempFile // 兼容各端 const rawFile =
// 生成水印文字 tempFile?.file instanceof File
const watermarkText = `${this.form.inspectionPoint || '未命名地点'} \n${this.getCurrentDate()}` ? tempFile.file
// 加水印(返回 File/Blob : tempFile instanceof File
const watermarked = await addWatermarkToImage(raw, watermarkText) ? tempFile
// 可选:移动端压缩(你已有方法,按需启用) : null
// const finalFile = await this.compressImageForMobile(watermarked) if (!rawFile) {
throw new Error("未获取到有效的 File 对象(仅支持 H5")
}
const finalFile = watermarked const watermarkText = `${this.form.inspectionPoint || "未命名地点"} \n${this.getCurrentDate()}`
// 预览:用本地 URL仅供前端显示 // 水印(返回 Blob 或 File
const previewUrl = URL.createObjectURL(finalFile) let watermarked = await addWatermarkToImage(rawFile, watermarkText)
this.img.push({ if (!(watermarked instanceof File)) {
url: previewUrl, // uni-file-picker 识别 url // 统一转回 File
name: finalFile.name || `image_${Date.now()}.jpg`, watermarked = this.blobToFile(
extname: 'jpg' watermarked,
}) rawFile.name || `image_${Date.now()}.jpg`
)
}
// 真正上传:**不要传 previewUrl 字符串**,而是传二进制 `file` // 压缩(仅 H5
// H5 下uni.uploadFile 支持传 `file: File` const finalFile = await this.compressImageForMobile(watermarked, {
const uploadedName = await this.uploadFileWithUni(finalFile) quality: 0.6,
// 回填后端返回的文件名/URL maxWidth: 1200,
this.form.ImgUrl.push(uploadedName) maxHeight: 1200,
}, mime: "image/jpeg"
})
// 用 uni.uploadFile 直接传二进制 // 预览(本地 blob URL
uploadFileWithUni(file) { const previewUrl = URL.createObjectURL(finalFile)
return new Promise((resolve, reject) => { this.img.push({
uni.uploadFile({ url: previewUrl,
url: UPLOAD_URL, name: finalFile.name || `image_${Date.now()}.jpg`,
name: 'file', // 后端接收字段名(按你的后端改) extname: "jpg"
file, // H5 直接传 File 对象(重点!) })
// 如果后端还需要额外字段:
// formData: { bizType: 'inspection' },
success: (res) => {
try {
const data = typeof res.data === 'string' ? JSON.parse(res.data) : res
.data
if (data.code === 200) {
// 假设后端返回 { code:200, fileName: 'xxx.jpg', url:'...' }
resolve(data.fileName || data.url)
} else {
reject(new Error(data.msg || '上传失败'))
}
} catch (e) {
reject(new Error('上传响应解析失败'))
}
},
fail: (err) => reject(err)
})
})
},
cancel() { // 上传H5 用 file 字段)
uni.reLaunch({ const uploadedName = await this.uploadFileWithUni(finalFile)
url: '/pages/work/index' this.form.ImgUrl.push(uploadedName)
})
},
joinList() { // 可选:延时释放预览 URL避免立即失效
return this.form.ImgUrl.join(',') setTimeout(() => {
}, try {
URL.revokeObjectURL(previewUrl)
} catch {}
}, 30000)
},
getCurrentDate() { // —— 仅 H5File 压缩canvas 尺寸+质量)——
const now = new Date() async compressImageForMobile(file, opts = {}) {
const y = now.getFullYear() const { quality = 0.6, maxWidth = 1200, maxHeight = 1200, mime = "image/jpeg" } = opts
const m = String(now.getMonth() + 1).padStart(2, '0') if (!(file instanceof File)) return file
const d = String(now.getDate()).padStart(2, '0')
const hh = String(now.getHours()).padStart(2, '0')
const mm = String(now.getMinutes()).padStart(2, '0')
const ss = String(now.getSeconds()).padStart(2, '0')
return `${y}-${m}-${d} ${hh}:${mm}:${ss}`
},
dialogConfirm() { const dataURL = await new Promise((resolve, reject) => {
if (this.msgType === 'success') { const reader = new FileReader()
uni.reLaunch({ reader.onload = () => resolve(reader.result)
url: '/pages/work/index' reader.onerror = () => reject(new Error("文件读取失败"))
}) reader.readAsDataURL(file)
} })
},
showMessage(type, text) { const img = await new Promise((resolve, reject) => {
this.msgType = type const image = new Image()
this.messageText = text image.onload = () => resolve(image)
this.$refs.alertDialog.open() image.onerror = () => reject(new Error("图片加载失败"))
}, image.src = dataURL
})
checkMobileBrowser() { const { w, h } = this.calcTargetSize(img.width, img.height, maxWidth, maxHeight)
const ua = navigator.userAgent.toLowerCase() const canvas = document.createElement("canvas")
const isMobile = /iphone|ipod|android|windows phone|mobile|blackberry/.test(ua) canvas.width = w
this.isMobileBrowser = isMobile || window.__uniAppWebview canvas.height = h
}, const ctx = canvas.getContext("2d")
// 计算目标尺寸 ctx.imageSmoothingQuality = "high"
calcTargetSize(imgW, imgH, maxW, maxH) { ctx.drawImage(img, 0, 0, w, h)
let w = imgW,
h = imgH
if (w > maxW || h > maxH) {
const ratio = Math.min(maxW / w, maxH / h)
w = Math.round(w * ratio)
h = Math.round(h * ratio)
}
return {
w,
h
}
},
// iOS 兼容 toBlob老 Safari const blob = await this.canvasToBlob(canvas, mime, quality)
canvasToBlob(canvas, type, quality) { if (!blob) return file
return new Promise((resolve) => { if (blob.size >= file.size) return file // 压缩后更大就不压了
if (canvas.toBlob) { return this.blobToFile(blob, file.name)
canvas.toBlob((blob) => resolve(blob), type, quality) },
} else {
// fallback: toDataURL -> Blob
const dataURL = canvas.toDataURL(type, quality)
const arr = dataURL.split(',')
const mime = arr[0].match(/:(.*?);/)[1]
const bstr = atob(arr[1])
let n = bstr.length
const u8arr = new Uint8Array(n)
while (n--) u8arr[n] = bstr.charCodeAt(n)
resolve(new Blob([u8arr], {
type: mime
}))
}
})
},
// H5: DataURL -> File // 计算目标尺寸
blobToFile(blob, filename) { calcTargetSize(imgW, imgH, maxW, maxH) {
return new File([blob], filename || `img_${Date.now()}.jpg`, { let w = imgW,
type: blob.type || 'image/jpeg' h = imgH
}) if (w > maxW || h > maxH) {
}, const ratio = Math.min(maxW / w, maxH / h)
w = Math.round(w * ratio)
h = Math.round(h * ratio)
}
return { w, h }
},
/** // toBlob 兼容
* 压缩图片(移动端友好) canvasToBlob(canvas, type, quality) {
* @param {File|Object|String} input H5: File小程序/APPtempFile 对象或临时路径 return new Promise((resolve) => {
* @param {Object} opts { quality: 0.6, maxWidth: 1200, maxHeight: 1200, mime: 'image/jpeg' } if (canvas.toBlob) {
* @returns Promise<File|string> H5 返回 File小程序/APP 返回压缩后的临时路径 canvas.toBlob((blob) => resolve(blob), type, quality)
*/ } else {
async compressImageForMobile(input, opts = {}) { const dataURL = canvas.toDataURL(type, quality)
const { const arr = dataURL.split(",")
quality = 0.6, const mime = arr[0].match(/:(.*?);/)[1]
maxWidth = 1200, const bstr = atob(arr[1])
maxHeight = 1200, let n = bstr.length
mime = 'image/jpeg' const u8arr = new Uint8Array(n)
} = opts while (n--) u8arr[n] = bstr.charCodeAt(n)
resolve(new Blob([u8arr], { type: mime }))
}
})
},
// #ifdef H5 // Blob -> File
// —— H5使用 canvas 压缩 —— // blobToFile(blob, filename) {
const file = input instanceof File ? input : (input?.file instanceof File ? input.file : null) return new File([blob], filename || `img_${Date.now()}.jpg`, {
if (!file) return input // 没拿到 File 就直接返回原始值 type: blob.type || "image/jpeg"
})
},
// 读取为 dataURL // H5: 用 uni.uploadFile 直接传二进制 File
const dataURL = await new Promise((resolve, reject) => { uploadFileWithUni(file) {
const reader = new FileReader() return new Promise((resolve, reject) => {
reader.onload = () => resolve(reader.result) uni.uploadFile({
reader.onerror = () => reject(new Error('文件读取失败')) url: UPLOAD_URL,
reader.readAsDataURL(file) name: "file",
}) file, // H5 传 File不要传 filePath
success: (res) => {
try {
const data = typeof res.data === "string" ? JSON.parse(res.data) : res.data
if (data.code === 200) {
resolve(data.fileName || data.url)
} else {
reject(new Error(data.msg || "上传失败"))
}
} catch (e) {
reject(new Error("上传响应解析失败"))
}
},
fail: (err) => reject(err)
})
})
},
// 图片加载 cancel() {
const img = await new Promise((resolve, reject) => { uni.reLaunch({ url: "/pages/work/index" })
const image = new Image() },
image.onload = () => resolve(image)
image.onerror = () => reject(new Error('图片加载失败'))
image.src = dataURL
})
const { joinList() {
w, return this.form.ImgUrl.join(",")
h },
} = this.calcTargetSize(img.width, img.height, maxWidth, maxHeight)
// 如果尺寸本来就不大,直接走质量压缩(或原图)
const canvas = document.createElement('canvas')
canvas.width = w
canvas.height = h
const ctx = canvas.getContext('2d')
ctx.imageSmoothingQuality = 'high'
ctx.drawImage(img, 0, 0, w, h)
const blob = await this.canvasToBlob(canvas, mime, quality) getCurrentDate() {
if (!blob) return file const now = new Date()
const y = now.getFullYear()
const m = String(now.getMonth() + 1).padStart(2, "0")
const d = String(now.getDate()).padStart(2, "0")
const hh = String(now.getHours()).padStart(2, "0")
const mm = String(now.getMinutes()).padStart(2, "0")
const ss = String(now.getSeconds()).padStart(2, "0")
return `${y}-${m}-${d} ${hh}:${mm}:${ss}`
},
// 若压缩后反而更大,则返回原图 dialogConfirm() {
if (blob.size > file.size) return file if (this.msgType === "success") {
uni.reLaunch({ url: "/pages/work/index" })
}
},
return this.blobToFile(blob, file.name) showMessage(type, text) {
// #endif this.msgType = type
this.messageText = text
this.$refs.alertDialog.open()
},
// #ifdef MP-WEIXIN || APP-PLUS checkMobileBrowser() {
// —— 小程序 / APP使用 uni.compressImage —— // const ua = navigator.userAgent.toLowerCase()
// 允许传入 input 为对象(如 tempFile或字符串路径 const isMobile = /iphone|ipod|android|windows phone|mobile|blackberry/.test(ua)
const srcPath = typeof input === 'string' ? this.isMobileBrowser = isMobile || window.__uniAppWebview
input : }
(input?.tempFilePath || input?.path || input?.filePath) },
onLoad(option) {
if (!srcPath) return input this.form.inspectionPoint = option.inspectionPoint || ""
this.form.inspectionRequirements = option.inspectionRequirements || ""
// uni.compressImage 文档quality 0-100部分端支持 width/height this.form.inspectionPointId = option.inspectionPointId || ""
const q = Math.max(1, Math.min(100, Math.round(quality * 100))) },
mounted() {
// 尝试带上 width/height端上不支持也会忽略 if (!BASE_URL) {
const compressed = await new Promise((resolve, reject) => { console.warn("[上传] baseUrl 未配置,当前上传地址可能异常:", UPLOAD_URL)
uni.compressImage({ }
src: srcPath, this.checkMobileBrowser()
quality: q, }
width: maxWidth,
height: maxHeight,
success: (res) => resolve(res.tempFilePath || res.apFilePath || res.target ||
res.path),
fail: (err) => reject(err)
})
})
return compressed
// #endif
},
},
onLoad(option) {
this.form.inspectionPoint = option.inspectionPoint || ''
this.form.inspectionRequirements = option.inspectionRequirements || ''
this.form.inspectionPointId = option.inspectionPointId || ''
},
mounted() {
this.checkMobileBrowser()
}
} }
</script> </script>