UNPKG

guci-date

Version:

A golden bottle of sake costs ten thousand yuan, and a jade plate costs ten thousand yuan.

83 lines (73 loc) 2.57 kB
const OSS = require('ali-oss'); const client = new OSS({ region: 'oss-cn-beijing', accessKeyId: 'LTAI5tSgyjpiqFK4aGi2geXi', accessKeySecret: 'IQd3MjCjqmxnZLaDjmH9bH1pMS6vJh', bucket: 'mz-app-develop', }); const chunkSize = 1024 * 1024; // 1MB export const uploadFileInChunksToOSS = async (fileName, file) => { try { // const { name, type } = file; // const fileName = getFileNameUUID(name); const totalChunks = Math.ceil(file.size / chunkSize); let currentChunk = 0; console.log(file) const uploadChunk = async (chunk) => { const partNumber = currentChunk + 1; const buffer = await fileToBuffer(file); const result = await client.uploadPart(fileName, partNumber, buffer, { headers: { 'Content-Type': 'file' }, // ...options }); currentChunk++; if (currentChunk < totalChunks) { const start = currentChunk * chunkSize; const end = Math.min(start + chunkSize, file.size); const nextChunk = file.slice(start, end); await uploadChunk(nextChunk); } else { await handleUploadComplete(fileName); } }; const start = currentChunk * chunkSize; const end = Math.min(start + chunkSize, file.size); const chunk = file.slice(start, end); await uploadChunk(chunk); } catch (e) { console.error('Error uploading file in chunks to OSS:', e); throw e; } }; const handleUploadComplete = async (fileName) => { try { const result = await client.initMultipartUpload(fileName); const uploadId = result.uploadId; const parts = []; for (let i = 1; i <= totalChunks; i++) { const part = await client.uploadPart(fileName, uploadId, i, `${fileName}-${i}`); parts.push({ PartNumber: i, ETag: part.ETag }); } const completeResult = await client.completeMultipartUpload(fileName, uploadId, parts); console.log('File uploaded to OSS, complete result:', completeResult); } catch (e) { console.error('Error completing multipart upload:', e); throw e; } }; const fileToBuffer = async (blob) => { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.onload = () => resolve(reader.result); reader.onerror = reject; reader.readAsArrayBuffer(blob); }); }; const getFileNameUUID = () => { function rx() { return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1) } return `${+new Date()}_${rx()}${rx()}` };