file转base64和base64转file


function base64toFile (dataurl, filename) {
    let arr = dataurl.split(',')
    let mime = arr[0].match(/:(.*?);/)[1]
    let suffix = mime.split('/')[1]
    let bstr = atob(arr[1])
    let n = bstr.length
    let u8arr = new Uint8Array(n)
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
    }
    return new File([u8arr], `${filename}.${suffix}`, {
        type: mime
    })
}
 

// 将file文件上传转化为base64进行显示
function getBase64(file) {
    return new Promise((resolve, reject) => {
        ///FileReader类就是专门用来读文件的
        const reader = new FileReader()
        //开始读文件
        //readAsDataURL: dataurl它的本质就是图片的二进制数据, 进行base64加密后形成的一个字符串,
        reader.readAsDataURL(file)
        // 成功和失败返回对应的信息,reader.result一个base64,可以直接使用
        reader.onload = () => resolve(reader.result)
        // 失败返回失败的信息
        reader.onerror = error => reject(error)
    })
}

公司里面input file获取文件并上传

 


            onWxSendImg(e) {
                let _this = this;
                _this.isLoading = true;
                if (e.target.files.length) {
                    let fileArr = Array.from(e.target.files);
                    fileArr.forEach(item => {
                        if (item.size > 20971520) {
                            _this.$notify({
                                message: "发送失败,文件限制20M",
                                duration: 2000
                            });
                            _this.isLoading = false;
                        } else {
                            let reader = new FileReader();
                            reader.readAsDataURL(item);
                            reader.onload = function (e) {
                                _this.toBase64(e.srcElement.result, e.type);
                            };
                        }
                    });
                }
            },
            toBase64(base64, type) {
                let that = this;
                let localData = base64.replace(/\r|\n/g, "").replace("data:image/jpg", "data:image/jpeg").replace("data:image/png", "data:image/jpeg");
                let wxData = localData.replace("data:image/jpeg;base64,", "").replace("data:image/jpg;base64,", "");
                let it = {
                    type: type,
                    base64: wxData
                };
                let file = that.base64ToFile(it);    // 转化图片
                let fileString = "";
                let formData = new FormData();
                formData.append("file", file);
                HttpUtil.getTkData("post", "mobilenet/analysis-report/order/file/upload", formData).then(res => {
                    fileString = String(res.fileUrl);
                    this.$emit('afterUpload', [{
                        file: file,
                        fileUrl: fileString,
                        fileId: res.fileId
                    }])
                    that.isLoading = false;
                }).catch((err) => {
                    console.log("走了catch");
                    that.isLoading = false;
                    that.$notify({
                        message: `${err.msg}`,
                        duration: 1000
                    });
                });
            },
            base64ToFile(data) {
                // 将base64解码
                var bytes = atob(data.base64);
                //var bytes = base64;
                var bytesCode = new ArrayBuffer(bytes.length);
                // 转换为类型化数组
                var byteArray = new Uint8Array(bytesCode);

                // 将base64转换为ascii码
                for (let i = 0; i < bytes.length; i++) {
                    byteArray[i] = bytes.charCodeAt(i);
                }
                // 生成Blob对象(文件对象)
                let name = data.name ? data.name : "default.png";
                let file = new File([bytesCode], name, { type: "image/png" });

                return file;
            },

你可能感兴趣的:(file转base64和base64转file)