153 lines
4.2 KiB
JavaScript
153 lines
4.2 KiB
JavaScript
const { ADMIN_API_BASE_URL, API_DOMAIN, REQUEST_TIMEOUT } = require('./config')
|
|
const request = require('./request')
|
|
|
|
function normalizeUploadResponse(response, fallbackMessage) {
|
|
if (response.statusCode === 401) {
|
|
throw new Error('登录已过期,请重新登录')
|
|
}
|
|
if (response.statusCode >= 400) {
|
|
const message = response.data && response.data.message ? response.data.message : fallbackMessage
|
|
throw new Error(message)
|
|
}
|
|
const payload = response.data
|
|
if (payload && typeof payload === 'object' && Object.prototype.hasOwnProperty.call(payload, 'code')) {
|
|
if (payload.code === 200) {
|
|
return payload.data
|
|
}
|
|
throw new Error(payload.message || fallbackMessage)
|
|
}
|
|
return payload
|
|
}
|
|
|
|
function preserveResponseId(rawText, payload) {
|
|
if (!payload || typeof payload !== 'object' || !payload.data || typeof payload.data !== 'object') {
|
|
return payload
|
|
}
|
|
const match = String(rawText || '').match(/"id"\s*:\s*"?(\d+)"?/)
|
|
if (match && match[1]) {
|
|
payload.data.id = match[1]
|
|
}
|
|
return payload
|
|
}
|
|
|
|
function uploadFile(options) {
|
|
const method = 'POST'
|
|
const baseUrl = options.baseUrl || ADMIN_API_BASE_URL
|
|
const url = `${baseUrl}${options.url}`
|
|
const signatureHeaders = request.buildSignatureHeaders({
|
|
url: options.url,
|
|
requestUrl: url,
|
|
method,
|
|
data: options.formData || {},
|
|
params: options.formData || {},
|
|
header: {
|
|
'Content-Type': 'multipart/form-data'
|
|
}
|
|
})
|
|
return new Promise((resolve, reject) => {
|
|
wx.uploadFile({
|
|
url,
|
|
filePath: options.filePath,
|
|
name: options.name,
|
|
timeout: options.timeout || REQUEST_TIMEOUT,
|
|
formData: options.formData || {},
|
|
header: signatureHeaders,
|
|
success(response) {
|
|
try {
|
|
const data = response.data ? preserveResponseId(response.data, JSON.parse(response.data)) : {}
|
|
resolve(normalizeUploadResponse({ ...response, data }, options.errorMessage || '上传失败'))
|
|
} catch (error) {
|
|
reject(error)
|
|
}
|
|
},
|
|
fail(error) {
|
|
reject(new Error(`文件上传失败:${url},原因:${error.errMsg || '未知错误'}`))
|
|
}
|
|
})
|
|
})
|
|
}
|
|
|
|
function chooseImageFilePaths(count) {
|
|
if (!Number.isInteger(count) || count < 1 || count > 9) {
|
|
throw new RangeError(`选择图片数量必须是 1-9,当前值:${count}`)
|
|
}
|
|
return new Promise((resolve, reject) => {
|
|
wx.chooseMedia({
|
|
count,
|
|
mediaType: ['image'],
|
|
sourceType: ['album', 'camera'],
|
|
sizeType: ['compressed'],
|
|
success(result) {
|
|
const filePaths = (result.tempFiles || []).map(file => file.tempFilePath).filter(Boolean)
|
|
resolve(filePaths)
|
|
},
|
|
fail(error) {
|
|
const message = error && error.errMsg ? error.errMsg : ''
|
|
if (message.includes('cancel')) {
|
|
resolve([])
|
|
return
|
|
}
|
|
reject(new Error(`选择图片失败:${message || '未知错误'}`))
|
|
}
|
|
})
|
|
})
|
|
}
|
|
|
|
async function chooseImageFilePath() {
|
|
const filePaths = await chooseImageFilePaths(1)
|
|
return filePaths[0] || ''
|
|
}
|
|
|
|
function uploadObjectFile(filePath) {
|
|
return uploadFile({
|
|
url: '/object-storage-file/upload',
|
|
filePath,
|
|
name: 'file',
|
|
errorMessage: '文件上传失败'
|
|
})
|
|
}
|
|
|
|
function resolveUploadedImagePreviewUrl(uploadResult, fallbackFilePath) {
|
|
const localPath = String(fallbackFilePath || '').trim()
|
|
if (localPath) {
|
|
return localPath
|
|
}
|
|
if (!uploadResult || typeof uploadResult !== 'object') {
|
|
return ''
|
|
}
|
|
const primaryUrl = String(uploadResult.primaryUrl || '').trim()
|
|
if (primaryUrl) {
|
|
return primaryUrl
|
|
}
|
|
return String(uploadResult.fileUrl || '').trim()
|
|
}
|
|
|
|
function uploadProfileImage(filePath) {
|
|
return uploadFile({
|
|
url: '/user/upload-profile-image',
|
|
baseUrl: API_DOMAIN,
|
|
filePath,
|
|
name: 'file',
|
|
errorMessage: '头像上传失败'
|
|
})
|
|
}
|
|
|
|
function uploadAvatar(filePath) {
|
|
return uploadFile({
|
|
url: '/user/upload-avatar',
|
|
baseUrl: API_DOMAIN,
|
|
filePath,
|
|
name: 'file',
|
|
errorMessage: '头像上传失败'
|
|
})
|
|
}
|
|
|
|
module.exports = {
|
|
chooseImageFilePaths,
|
|
chooseImageFilePath,
|
|
uploadObjectFile,
|
|
resolveUploadedImagePreviewUrl,
|
|
uploadAvatar,
|
|
uploadProfileImage
|
|
}
|