/** * Purpose: fileApi supports upload.js by holding or executing the file api page or API role. * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. */ const fileApi = require('../api/file') /** * Purpose: getFileSystemManager supports upload.js by holding or executing the get file system manager page or API role. * Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow. */ function getFileSystemManager() { return wx.getFileSystemManager() } /** * Purpose: getFileInfo supports upload.js by holding or executing the get file info page or API role. * Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow. */ function getFileInfo(filePath) { return new Promise((resolve, reject) => { wx.getFileInfo({ filePath, success: resolve, fail: reject }) }) } /** * Purpose: readFileBuffer supports upload.js by holding or executing the read file buffer page or API role. * Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow. */ function readFileBuffer(filePath) { return new Promise((resolve, reject) => { getFileSystemManager().readFile({ filePath, success: result => resolve(result.data), fail: reject }) }) } /** * Purpose: writeChunkFile supports upload.js by holding or executing the write chunk file page or API role. * Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow. */ function writeChunkFile(filePath, data) { return new Promise((resolve, reject) => { getFileSystemManager().writeFile({ filePath, data, encoding: 'binary', success: resolve, fail: reject }) }) } /** * Purpose: removeFile supports upload.js by holding or executing the remove file page or API role. * Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow. */ function removeFile(filePath) { return new Promise(resolve => { getFileSystemManager().unlink({ filePath, success: resolve, fail: resolve }) }) } /** * Purpose: normalizeSelectedFiles supports upload.js by holding or executing the normalize selected files page or API role. * Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow. */ 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) } /** * Purpose: createFingerprint supports upload.js by holding or executing the create fingerprint page or API role. * Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow. */ 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)}` } /** * Purpose: resolveContentType supports upload.js by holding or executing the resolve content type page or API role. * Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow. */ 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' } /** * Purpose: uploadSingleFile supports upload.js by holding or executing the upload single file page or API role. * Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow. */ 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 } /** * Purpose: uploadImageFiles supports upload.js by holding or executing the upload image files page or API role. * Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow. */ 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 } /** * Purpose: chooseImageFiles supports upload.js by holding or executing the choose image files page or API role. * Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow. */ 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 }