Files
im-uniapp/api/common/upload.js

216 lines
6.6 KiB
JavaScript
Raw Normal View History

import { getToken } from '@/util/auth'
2026-04-17 12:07:27 +08:00
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)
}
})
})
2025-07-12 10:37:32 +08:00
}
/**
* 文件上传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'],
2026-04-17 12:07:27 +08:00
maxSize = 200,
2025-07-12 10:37:32 +08:00
extraData = 1
} = options
return new Promise((resolve, reject) => {
2026-04-17 12:07:27 +08:00
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('文件路径为空'))
2025-07-12 10:37:32 +08:00
return
}
2026-04-17 12:07:27 +08:00
const ext = (fileName.split('.').pop() || '').toLowerCase()
if (allowedTypes && ext && !allowedTypes.includes(ext)) {
reject(new Error(`文件格式不正确,请上传 ${allowedTypes.join('/')} 格式文件!`))
2025-07-12 10:37:32 +08:00
return
}
2026-04-17 12:07:27 +08:00
if (maxSize && fileSize > 0 && fileSize / 1024 / 1024 > maxSize) {
reject(new Error(`上传文件大小不能超过 ${maxSize} MB`))
2025-07-12 10:37:32 +08:00
return
}
2026-04-17 12:07:27 +08:00
let realPath = filePath
2025-07-12 10:37:32 +08:00
// #ifdef APP-PLUS
2026-04-17 12:07:27 +08:00
if (typeof plus !== 'undefined' && plus.io && realPath && !realPath.startsWith('file://') && !realPath.startsWith('/')) {
try {
realPath = plus.io.convertLocalFileSystemURL(realPath)
} catch (e) {
console.warn('[uploadFile] 路径转换失败,使用原始路径', e)
2025-07-12 10:37:32 +08:00
}
}
// #endif
2026-04-17 12:07:27 +08:00
console.log('[uploadFile] 开始上传文件:', { fileName, realPath, fileSize, type: file?.type })
2025-07-12 10:37:32 +08:00
uni.uploadFile({
url: BASE_URL + '/system/oss/upload',
2026-04-17 12:07:27 +08:00
filePath: realPath,
2025-07-12 10:37:32 +08:00
name: 'file',
2026-04-17 12:07:27 +08:00
formData: { isPublic: extraData },
header: { Authorization: 'Bearer ' + getToken() },
2025-07-12 10:37:32 +08:00
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,
2026-04-17 12:07:27 +08:00
originalName: fileName
2025-07-12 10:37:32 +08:00
})
} else {
2026-04-17 12:07:27 +08:00
reject(new Error(data.msg || '上传失败'))
2025-07-12 10:37:32 +08:00
}
} catch (e) {
console.error('[uploadFile] 解析返回数据失败:', e, res.data)
2026-04-17 12:07:27 +08:00
reject(new Error('上传返回格式错误'))
2025-07-12 10:37:32 +08:00
}
},
fail: (err) => {
console.error('[uploadFile] 上传接口调用失败:', err)
2026-04-17 12:07:27 +08:00
reject(new Error(err?.errMsg || err?.message || '上传失败'))
2025-07-12 10:37:32 +08:00
}
})
})
}
/**
* 批量上传文件
* @param {Array} files - 文件数组
* @param {Object} options - 上传选项
* @returns {Promise} 返回上传结果数组
*/
2026-04-17 12:07:27 +08:00
export async function uploadFiles(files, options = {}) {
2025-07-12 10:37:32 +08:00
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} 返回文件信息数组
*/
2026-04-17 12:07:27 +08:00
export async function getFilesByIds(ossIds) {
2025-07-12 10:37:32 +08:00
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 || '获取文件信息失败')
}
})
}