js 大文件分片

将大文件分为大小为5M的多个分片,并且每给文件名为 原文件名+ “_” + 文件后缀

function splitFile(files) {
        return new Promise(((resolve, reject) => {
            const fileName = files.name
            const fileSize = files.size
            // 	5M = 5242880B
            const splitSize = 5242880, 
            filesList = [], 
            filesListLength = Math.ceil(fileSize / splitSize),
            suffix = /\.([0-9A-z]+)$/.exec(fileName)[1]
            const name = fileName.substring(0, fileName.lastIndexOf(suffix)-1)
            let index = 0
            for (let i = 0; i < filesListLength; i++) {
                var file = files.slice(index , index + splitSize)
                let file1 = new File([file], `${name}_${i}.${suffix}`, { type: file.type })
                const item = {
                    file: file1,
                    sequence: i,
                    uploadId: null,
                }
                index += splitSize
                filesList.push(item)
            }
            let json = {files: filesList, size: fileSize}
            resolve(json)
        }))
    }

你可能感兴趣的:(javascript,前端)