216 lines
6.6 KiB
JavaScript
216 lines
6.6 KiB
JavaScript
import { getToken } from '@/util/auth'
|
||
import request, { BASE_URL } from "@/util/oaRequest"
|
||
|
||
export function uploadImage(filePath) {
|
||
console.log('[uploadImage] 开始上传:', filePath)
|
||
return new Promise((resolve, reject) => {
|
||
uni.uploadFile({
|
||
url: BASE_URL + '/system/oss/upload',
|
||
filePath,
|
||
name: 'file',
|
||
header: {
|
||
'Authorization': 'Bearer ' + getToken()
|
||
},
|
||
success: (res) => {
|
||
console.log('[uploadImage] 上传响应:', res)
|
||
try {
|
||
const data = typeof res.data === 'string' ? JSON.parse(res.data) : res.data
|
||
if (data.code === 200) {
|
||
console.log('[uploadImage] 上传成功:', data.data)
|
||
resolve(data.data) // { ossId, url }
|
||
} else {
|
||
console.error('[uploadImage] 上传失败:', data)
|
||
reject(data.msg || '上传失败')
|
||
}
|
||
} catch (e) {
|
||
console.error('[uploadImage] 解析返回数据失败:', e, res.data)
|
||
reject('上传返回格式错误')
|
||
}
|
||
},
|
||
fail: (err) => {
|
||
console.error('[uploadImage] 上传接口调用失败:', err)
|
||
reject(err)
|
||
}
|
||
})
|
||
})
|
||
}
|
||
|
||
/**
|
||
* 文件上传API
|
||
* @param {Object} file - 文件对象
|
||
* @param {string} file.path - 文件路径
|
||
* @param {string} file.name - 文件名
|
||
* @param {number} file.size - 文件大小
|
||
* @param {string} file.type - 文件类型
|
||
* @param {Object} options - 上传选项
|
||
* @param {Array} options.allowedTypes - 允许的文件类型扩展名数组
|
||
* @param {number} options.maxSize - 最大文件大小(MB)
|
||
* @param {number} options.extraData - 额外数据,默认为1
|
||
* @returns {Promise} 返回上传结果 { ossId, url, fileName, originalName }
|
||
*/
|
||
export function uploadFile(file, options = {}) {
|
||
const {
|
||
allowedTypes = ['doc', 'xls', 'ppt', 'txt', 'pdf', 'docx', 'xlsx', 'png', 'jpg', 'jpeg', 'zip', 'rar', '7z', 'dwg'],
|
||
maxSize = 200,
|
||
extraData = 1
|
||
} = options
|
||
|
||
return new Promise((resolve, reject) => {
|
||
const fileName = file?.name || file?.fileName || file?.originalName || ''
|
||
const filePath = file?.path || file?.tempFilePath || file?.url || file?.filePath || ''
|
||
const fileSize = Number(file?.size || 0)
|
||
|
||
console.log('[uploadFile] 入参:', { fileName, filePath, fileSize, type: file?.type, raw: file })
|
||
|
||
if (!filePath) {
|
||
reject(new Error('文件路径为空'))
|
||
return
|
||
}
|
||
|
||
const ext = (fileName.split('.').pop() || '').toLowerCase()
|
||
if (allowedTypes && ext && !allowedTypes.includes(ext)) {
|
||
reject(new Error(`文件格式不正确,请上传 ${allowedTypes.join('/')} 格式文件!`))
|
||
return
|
||
}
|
||
|
||
if (maxSize && fileSize > 0 && fileSize / 1024 / 1024 > maxSize) {
|
||
reject(new Error(`上传文件大小不能超过 ${maxSize} MB!`))
|
||
return
|
||
}
|
||
|
||
let realPath = filePath
|
||
// #ifdef APP-PLUS
|
||
if (typeof plus !== 'undefined' && plus.io && realPath && !realPath.startsWith('file://') && !realPath.startsWith('/')) {
|
||
try {
|
||
realPath = plus.io.convertLocalFileSystemURL(realPath)
|
||
} catch (e) {
|
||
console.warn('[uploadFile] 路径转换失败,使用原始路径', e)
|
||
}
|
||
}
|
||
// #endif
|
||
|
||
console.log('[uploadFile] 开始上传文件:', { fileName, realPath, fileSize, type: file?.type })
|
||
|
||
uni.uploadFile({
|
||
url: BASE_URL + '/system/oss/upload',
|
||
filePath: realPath,
|
||
name: 'file',
|
||
formData: { isPublic: extraData },
|
||
header: { Authorization: 'Bearer ' + getToken() },
|
||
success: (res) => {
|
||
console.log('[uploadFile] 上传响应:', res)
|
||
try {
|
||
const data = typeof res.data === 'string' ? JSON.parse(res.data) : res.data
|
||
if (data.code === 200) {
|
||
resolve({
|
||
ossId: data.data.ossId,
|
||
url: data.data.url,
|
||
fileName: data.data.fileName,
|
||
originalName: fileName
|
||
})
|
||
} else {
|
||
reject(new Error(data.msg || '上传失败'))
|
||
}
|
||
} catch (e) {
|
||
console.error('[uploadFile] 解析返回数据失败:', e, res.data)
|
||
reject(new Error('上传返回格式错误'))
|
||
}
|
||
},
|
||
fail: (err) => {
|
||
console.error('[uploadFile] 上传接口调用失败:', err)
|
||
reject(new Error(err?.errMsg || err?.message || '上传失败'))
|
||
}
|
||
})
|
||
})
|
||
}
|
||
|
||
/**
|
||
* 批量上传文件
|
||
* @param {Array} files - 文件数组
|
||
* @param {Object} options - 上传选项
|
||
* @returns {Promise} 返回上传结果数组
|
||
*/
|
||
export async function uploadFiles(files, options = {}) {
|
||
const {
|
||
allowedTypes = ['doc', 'xls', 'ppt', 'txt', 'pdf', 'docx', 'xlsx', 'png', 'jpg', 'jpeg', 'zip', 'rar', '7z', 'dwg'],
|
||
maxSize = 200,
|
||
extraData = 1,
|
||
onProgress = null
|
||
} = options
|
||
|
||
return new Promise((resolve, reject) => {
|
||
if (!files || files.length === 0) {
|
||
resolve([])
|
||
return
|
||
}
|
||
|
||
const results = []
|
||
let completedCount = 0
|
||
let hasError = false
|
||
|
||
files.forEach((file, index) => {
|
||
uploadFile(file, { allowedTypes, maxSize, extraData })
|
||
.then(result => {
|
||
results[index] = result
|
||
completedCount++
|
||
|
||
// 调用进度回调
|
||
if (onProgress) {
|
||
onProgress({
|
||
index,
|
||
file,
|
||
result,
|
||
progress: (completedCount / files.length) * 100
|
||
})
|
||
}
|
||
|
||
// 所有文件上传完成
|
||
if (completedCount === files.length && !hasError) {
|
||
resolve(results)
|
||
}
|
||
})
|
||
.catch(error => {
|
||
hasError = true
|
||
console.error(`文件 ${file.name} 上传失败:`, error)
|
||
reject(new Error(`文件 "${file.name}" 上传失败: ${error.message || error}`))
|
||
})
|
||
})
|
||
})
|
||
}
|
||
|
||
/**
|
||
* 根据OSS ID列表获取文件信息
|
||
* @param {Array} ossIds - OSS ID数组
|
||
* @returns {Promise} 返回文件信息数组
|
||
*/
|
||
// 查询OSS对象基于id串
|
||
export function listByIds(ossId) {
|
||
return request({
|
||
url: '/system/oss/listByIds/' + ossId,
|
||
method: 'get'
|
||
})
|
||
}
|
||
|
||
/**
|
||
* 根据OSS ID列表获取文件信息
|
||
* @param {Array} ossIds - OSS ID数组
|
||
* @returns {Promise} 返回文件信息数组
|
||
*/
|
||
export async function getFilesByIds(ossIds) {
|
||
if (!ossIds || ossIds.length === 0) {
|
||
return Promise.resolve([])
|
||
}
|
||
|
||
const ossIdString = Array.isArray(ossIds) ? ossIds.join(',') : ossIds
|
||
|
||
return request({
|
||
url: '/system/oss/listByIds/' + ossIdString,
|
||
method: 'get'
|
||
}).then(response => {
|
||
if (response.code === 200) {
|
||
return response.data || []
|
||
} else {
|
||
throw new Error(response.msg || '获取文件信息失败')
|
||
}
|
||
})
|
||
} |