Files
JayuCloud/YumiNail-Admin-Program/utils/upload.js
T

199 lines
5.2 KiB
JavaScript

const fileApi = require('../api/file')
function getFileSystemManager() {
return wx.getFileSystemManager()
}
function getFileInfo(filePath) {
return new Promise((resolve, reject) => {
wx.getFileInfo({
filePath,
success: resolve,
fail: reject
})
})
}
function readFileBuffer(filePath) {
return new Promise((resolve, reject) => {
getFileSystemManager().readFile({
filePath,
success: result => resolve(result.data),
fail: reject
})
})
}
function writeChunkFile(filePath, data) {
return new Promise((resolve, reject) => {
getFileSystemManager().writeFile({
filePath,
data,
encoding: 'binary',
success: resolve,
fail: reject
})
})
}
function removeFile(filePath) {
return new Promise(resolve => {
getFileSystemManager().unlink({
filePath,
success: resolve,
fail: resolve
})
})
}
function normalizeSelectedFiles(files) {
return (Array.isArray(files) ? files : []).map((item, index) => {
if (typeof item === 'string') {
return {
tempFilePath: item,
fileName: `image-${index + 1}.jpg`
}
}
return {
tempFilePath: item.tempFilePath || item.path || '',
fileName: item.fileName || item.name || `image-${index + 1}.jpg`
}
}).filter(item => item.tempFilePath)
}
function createFingerprint(seed) {
let hash = 0
const text = String(seed || '')
for (let index = 0; index < text.length; index += 1) {
hash = ((hash << 5) - hash) + text.charCodeAt(index)
hash |= 0
}
return `mini-${Math.abs(hash)}`
}
function resolveContentType(fileName) {
const value = String(fileName || '').toLowerCase()
if (value.endsWith('.png')) {
return 'image/png'
}
if (value.endsWith('.webp')) {
return 'image/webp'
}
if (value.endsWith('.gif')) {
return 'image/gif'
}
return 'image/jpeg'
}
async function uploadSingleFile(file, scene, onProgress) {
const fileInfo = await getFileInfo(file.tempFilePath)
const buffer = await readFileBuffer(file.tempFilePath)
const contentType = resolveContentType(file.fileName)
const session = await fileApi.initChunkUpload({
fileName: file.fileName,
fileSize: fileInfo.size,
contentType,
fileFingerprint: createFingerprint(`${file.fileName}|${fileInfo.size}|${file.tempFilePath}`),
scene
})
const uploadedChunkSet = new Set(session.uploadedChunks || [])
let uploadedBytes = 0
const chunkSize = Number(session.chunkSize || 0)
const totalChunks = Number(session.totalChunks || 0)
if (!chunkSize || !totalChunks) {
throw new Error('上传会话初始化失败')
}
Array.from(uploadedChunkSet).forEach(chunkIndex => {
const start = chunkIndex * chunkSize
const end = Math.min(start + chunkSize, fileInfo.size)
uploadedBytes += Math.max(end - start, 0)
})
onProgress(Math.min((uploadedBytes / Math.max(fileInfo.size, 1)) * 100, 100))
for (let chunkIndex = 0; chunkIndex < totalChunks; chunkIndex += 1) {
if (uploadedChunkSet.has(chunkIndex)) {
continue
}
const start = chunkIndex * chunkSize
const end = Math.min(start + chunkSize, fileInfo.size)
const chunkBuffer = buffer.slice(start, end)
const chunkPath = `${wx.env.USER_DATA_PATH}/${session.uploadId}-${chunkIndex}.part`
await writeChunkFile(chunkPath, chunkBuffer)
try {
await fileApi.uploadChunkFile({
filePath: chunkPath,
uploadId: session.uploadId,
chunkIndex,
totalChunks,
onProgress(progress) {
const loaded = Number(progress && progress.totalBytesSent) || 0
const currentBytes = Math.min(loaded, end - start)
const percent = ((uploadedBytes + currentBytes) / Math.max(fileInfo.size, 1)) * 100
onProgress(Math.min(percent, 99.9))
}
})
} finally {
await removeFile(chunkPath)
}
uploadedBytes += (end - start)
onProgress(Math.min((uploadedBytes / Math.max(fileInfo.size, 1)) * 100, 99.9))
}
const result = await fileApi.completeChunkUpload(session.uploadId)
onProgress(100)
return result
}
async function uploadImageFiles(options) {
const files = normalizeSelectedFiles(options && options.files)
const scene = options && options.scene ? options.scene : 'admin-product-image'
const onProgress = typeof options.onProgress === 'function' ? options.onProgress : () => {}
const results = []
for (let index = 0; index < files.length; index += 1) {
const basePercent = (index / Math.max(files.length, 1)) * 100
const filePercentSize = 100 / Math.max(files.length, 1)
const result = await uploadSingleFile(files[index], scene, percent => {
onProgress(Math.min(basePercent + (percent / 100) * filePercentSize, 100))
})
results.push(result)
}
onProgress(100)
return results
}
function chooseImageFiles(options) {
const config = options || {}
return new Promise((resolve, reject) => {
wx.chooseMedia({
count: config.count || 9,
mediaType: ['image'],
sourceType: ['album', 'camera'],
success: result => {
resolve(normalizeSelectedFiles(result.tempFiles || []))
},
fail: reject
})
})
}
module.exports = {
chooseImageFiles,
uploadImageFiles
}