| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889 |
- /**
- * 报销附件:拍照/相册 → /attachments/upload(multipart,已在加密排除路径)
- * 返回附件对象列表(含 id),提交后需 bindAttachments
- */
- import { API_BASE, TOKEN_KEY } from '@/config/api'
- function parseBody(raw) {
- try {
- return JSON.parse(typeof raw === 'string' ? raw : String(raw || ''))
- } catch {
- return {}
- }
- }
- function getToken() {
- const raw = uni.getStorageSync(TOKEN_KEY)
- return typeof raw === 'string' ? raw.trim() : raw ? String(raw).trim() : ''
- }
- /**
- * @param {{ bizType?: string, bizId?: string|number, maxCount?: number, currentCount?: number }} opts
- * @returns {Promise<Array<{ id: string, fileName?: string, localPath?: string }>>}
- */
- export async function chooseAndUploadBxAttachments(opts = {}) {
- const bizType = opts.bizType || 'reimburse_apply'
- const bizId = opts.bizId != null ? String(opts.bizId) : '0'
- const maxCount = opts.maxCount != null ? opts.maxCount : 6
- const currentCount = opts.currentCount || 0
- const remain = maxCount - currentCount
- if (remain <= 0) {
- uni.showToast({ title: `最多上传${maxCount}张`, icon: 'none' })
- return []
- }
- const choose = await new Promise((resolve) => {
- uni.chooseImage({
- count: remain,
- sizeType: ['compressed'],
- sourceType: ['album', 'camera'],
- success: (res) => resolve(res),
- fail: () => resolve(null)
- })
- })
- if (!choose?.tempFilePaths?.length) return []
- const token = getToken()
- const uploadUrl = `${API_BASE}/attachments/upload?biz_type=${encodeURIComponent(bizType)}&biz_id=${encodeURIComponent(bizId)}`
- const uploaded = []
- uni.showLoading({ title: '上传中...' })
- try {
- for (const filePath of choose.tempFilePaths) {
- const uploadRes = await new Promise((ok, fail) => {
- uni.uploadFile({
- url: uploadUrl,
- filePath,
- name: 'file',
- header: {
- Authorization: token ? `Bearer ${token}` : ''
- },
- success: ok,
- fail
- })
- })
- if (uploadRes.statusCode === 401) {
- uni.showToast({ title: '登录已失效', icon: 'none' })
- break
- }
- const body = parseBody(uploadRes.data)
- // bx: code===0
- if (body.code !== 0 || !body.data?.id) {
- uni.showToast({ title: body.msg || body.message || '上传失败', icon: 'none' })
- break
- }
- uploaded.push({
- id: String(body.data.id),
- fileName: body.data.fileName || body.data.file_name || '',
- localPath: filePath
- })
- }
- } catch (e) {
- uni.showToast({
- title: e instanceof Error ? e.message : '上传失败',
- icon: 'none'
- })
- } finally {
- uni.hideLoading()
- }
- return uploaded
- }
|