美文网首页
关于上传文件方法的封装

关于上传文件方法的封装

作者: 本萌妹 | 来源:发表于2021-07-21 15:59 被阅读0次

export default class FileTools {

    /**

     * @method fileSizeFormat    格式化文件大小文本

     * @param {number} fileSize  要格式化的文本大小,单位为Byte

     * @param {number} precision 取小数点后几位,默认2位

     * @param {string[]} units   要格式化的单位文本,顺序为从小到大, 默认为['B', 'KB', 'MB', 'GB', 'TB', 'PB']

     * @return {string}          返回格式化后的文件大小字符串

     */

    static fileSizeFormat(fileSize, precision = 2, units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']) {

        let p = 0

        while (fileSize >= 1024 && p < units.length) {

            fileSize = fileSize / 1024

            p++

        }

        return fileSize.toFixed(precision) + units[p]

    }

    /***

     * @method fileToBase64        文件对象转base64(异步)

     * @param {File} file          要解析的文件对象

     * @param {function} callback  解析成功的回调函数

     * @param {function} callerror 解析失败的回调函数

     */

    static fileToBase64(file, callback, callerror) {

        const fileReader = new FileReader()

        fileReader.readAsDataURL(file)

        fileReader.onload = (e) => {

            const [base64Str, base64Length] = [e.target.result, e.target.result.length]

            const result = {

                base64: base64Str,

                base64Size: base64Length,

                base64FormatSize: this.fileSizeFormat(base64Length),

                name: file.name,

                lastModified: file.lastModified,

                size: file.size,

                formatSize: this.fileSizeFormat(file.size),

                type: file.type,

            }

            if (callback) callback(result)

        }

        fileReader.onerror = (e) => {

            fileReader.abort()

            if (callerror) callerror(e)

        }

    }

    /***

     * @method fileToBase64 文件对象转base64 Promise版

     * @param  {File} file 要解析的文件对象

     * @return {Promise} 返回一个Promise对象,可链式调用then和catch

     */

    static fileToBase64Promise(file) {

        return new Promise((resolve, reject) => {

            this.fileToBase64(

                file,

                (result) => {

                    resolve(result)

                },

                (error) => {

                    reject(error)

                }

            )

        })

    }

    /***

     * @method fileToBase64List          文件列表转base64(异步)

     * @param {FileList|File[]} files    要解析的文件对象列表,类型应为FileList对象或元素为Flie对象的数组

     * @param {function} callback        解析成功的回调函数

     * @param {function} callerror       解析失败的回调函数

     */

    static fileToBase64List(files, callback, callerror) {

        const promiseList = []

        for (let i = 0; i < files.length; i++) {

            promiseList.push(this.fileToBase64Promise(files[i]))

        }

        Promise.all(promiseList)

            .then((result) => {

                if (callback) callback(result)

            })

            .catch((error) => {

                if (callerror) callerror(error)

            })

    }

    /***

     * @method fileToBase64ListPromise   文件列表转base64 Promise版(异步)

     * @param {FileList|File[]} files    要解析的文件对象列表,类型应为FileList对象或元素为Flie对象的数组

     * @param {function} callback        解析成功的回调函数

     * @param {function} callerror       解析失败的回调函数

     */

    static fileToBase64ListPromise(files) {

        return new Promise((resolve, reject) => {

            this.fileToBase64List(files, (result) => {

                resolve(result)

            }, (error) => {

                reject(error)

            })

        })

    }

    /**

     * @method base64ToFile        base64字符串转文件并拉起下载

     * @param {string} base64Data  要转换的文件内容的base64字符串

     * @param {string} fileName    转换后的文件名

     */

    static base64ToFile(base64Data, fileName) {

        const eleLink = document.createElement('a')

        eleLink.download = fileName

        eleLink.style.display = 'none'

        eleLink.href = base64Data

        document.body.appendChild(eleLink)

        eleLink.click()

        document.body.removeChild(eleLink)

    }

    // arraybuffer类型转16进制字符串

    static ab2str(buf) {

        return Array.prototype.map

            .call(new Uint8Array(buf), (x) => ("00" + x.toString(16)).slice(-2))

            .join("");

    }

    //16进制字符串 转 ArrayBuffer

    static str2ab(str) {

        let typedArray = new Uint8Array(

            str.match(/[\da-f]{2}/gi).map(function (h) {

                return parseInt(h, 16);

            })

        );

        return typedArray.buffer

    }

    /***

     * @method fileToString        文件对象转String(异步)

     * @param {File} file          要解析的文件对象

     * @param {function} callback  解析成功的回调函数

     * @param {function} callerror 解析失败的回调函数

     */

    static fileToString(file, callback, callerror) {

        const fileReader = new FileReader()

        fileReader.onload = (e) => {

            let fileString = ''

            this.abToStr(e.target.result, (str) => {

                fileString = str

            })

            const result = {

                fileString,

                name: file.name,

                size: file.size,

                type: file.type,

            }

            if (callback) callback(result)

        }

        fileReader.onerror = (e) => {

            if (callerror) callerror(e)

        }

        readIcon.readAsArrayBuffer(files[i]);

    }

    /***

     * @method fileToStringPromise 文件对象转String Promise版

     * @param  {File} file 要解析的文件对象

     * @return {Promise} 返回一个Promise对象,可链式调用then和catch

     */

    static fileToStringPromise(file) {

        return new Promise((resolve, reject) => {

            this.fileToString(

                file,

                (result) => {

                    resolve(result)

                },

                (error) => {

                    reject(error)

                }

            )

        })

    }

    /***

     * @method fileToStringList          文件列表转String(异步)

     * @param {FileList|File[]} files    要解析的文件对象列表,类型应为FileList对象或元素为Flie对象的数组

     * @param {function} callback        解析成功的回调函数

     * @param {function} callerror       解析失败的回调函数

     */

    static fileToStringList(files, callback, callerror) {

        const promiseList = []

        for (let i = 0; i < files.length; i++) {

            promiseList.push(this.fileToStringPromise(files[i]))

        }

        Promise.all(promiseList)

            .then((result) => {

                if (callback) callback(result)

            })

            .catch((error) => {

                if (callerror) callerror(error)

            })

    }

    /***

     * @method fileToStringListPromise   文件列表转String Promise版(异步)

     * @param {FileList|File[]} files    要解析的文件对象列表,类型应为FileList对象或元素为Flie对象的数组

     * @param {function} callback        解析成功的回调函数

     * @param {function} callerror       解析失败的回调函数

     */

    static fileToStringListPromise(files) {

        return new Promise((resolve, reject) => {

            this.fileToStringList(files, (result) => {

                resolve(result)

            }, (error) => {

                reject(error)

            })

        })

    }

    /**

     * @method funDownload        字符串转文件并拉起下载

     * @param {string} content  要转换的文件内容的字符串

     * @param {string} fileName    转换后的文件名

     */

    static funDownload(content, filename) {

        const eleLink = document.createElement("a");

        eleLink.download = filename;

        eleLink.style.display = "none";

        const blob = new Blob([content]);

        eleLink.href = URL.createObjectURL(blob);

        document.body.appendChild(eleLink);

        eleLink.click();

        document.body.removeChild(eleLink);

    }

}

相关文章

网友评论

      本文标题:关于上传文件方法的封装

      本文链接:https://www.haomeiwen.com/subject/awpjmltx.html