图片上传前预览、压缩、转blob、转formData等操作

时间:2024-03-12 13:27:20

  直接上代码吧:

<template>
<div>
    <div class="header">添加淘宝买号</div>
    <div class="tips">
        <p class="font16">注意事项</p>
        <p class="font14">买号采用人工审核,提交后0.5个工作日内完成审核,请耐心等待,新手务必认真准确填写。</p>
    </div>
    <el-form ref="taobao" :model="taobaoInfo" label-width="100px" class="miForm">
        <el-form-item label="淘宝买号">
            <el-input v-model="taobaoInfo.name" placeholder="请输入淘宝的会员名"></el-input>
        </el-form-item>
        <el-form-item label="买号等级">
            <el-select v-model="taobaoInfo.level" placeholder="请选择买号星级">
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
            </el-select>
        </el-form-item>
    </el-form>
    <div class="upload">
        <img v-if="src" :src="src" alt="user image" height="100%" width="100%">
        <input type="file" @change="uploadIMG" ref="file" id="file">
        <label for="file"><i class="el-icon-plus"></i></label>
        <div class="del"><i class="el-icon-error" @click="delImg"></i></div>
    </div>
</div>
</template>
<script type="ecmascript-6">
export default {
    name:\'taobao\',
    data(){
        return {
            taobaoInfo:{},
            options:[
                {label:\'一心\',value:1},
                {label:\'二心\',value:2},
                {label:\'三心\',value:3},
                {label:\'四心\',value:4},
                {label:\'五心\',value:5},
                {label:\'一钻\',value:6},
                {label:\'二钻\',value:7},
                {label:\'三钻\',value:8},
                {label:\'四钻\',value:9},
                {label:\'五钻\',value:10}
            ],
            src: \'\'// 转base64码后的data字段
        }
    },
    methods:{
        getFile (file) {
            let _this = this
            if (!file || !window.FileReader) return // 看支持不支持FileReader 
            if (/^image/.test(file.type)) { 
                //创建一个reader 
                let reader = new FileReader() 
                reader.readAsDataURL(file) // 这里是最关键的一步,转换就在这里 
                reader.onloadend = function () { 
                    _this.src = this.result 

                    let result = this.result; 
                    let img = new Image(); 
                    img.src = result; 
                    console.log("未压缩前的图片大小:" + result.length); 
                    img.onload = function() {
                        let data = _this.compress(img);

                        let blob = _this.dataURItoBlob(data); 
                        console.log("base64转blob对象:" + blob); 
                        var formData = new FormData(); 
                        formData.append("file", blob); 
                        console.log("将blob对象转成formData对象:" + formData.get("file"));

                        let config = { 
                            headers: { "Content-Type": "multipart/form-data" } 
                        }; 
                        // 发送请求; 
                        _this.axios.post(_this.uploadUrl.url, formData, config).then(res => { 
                            if (res.data.code == 200) { 
                                _this.$emit( "getImgsrc", res.data.data.resultftphost, res.data.data.resulturl ); 
                            } else { 
                                _this.$message({ 
                                    message: "图片上传失败,请重试", 
                                    type: "warning" 
                                }); 
                            } 
                        }); 
                    }
                }
            }
        },
        uploadIMG(e) { 
            let files = e.target.files || e.dataTransfer.files; 
            if (!files.length) return; 
            this.picavalue = files[0]; 
            console.log("图片大小:" + this.picavalue.size / 1024 + "kb"); 
            if (this.picavalue.size / 1024 > 5000) { 
                this.$message({
                    message: "图片过大不支持上传", 
                    type: "warning" 
                }); 
            } else { 
                this.getFile(this.picavalue); 
            } 
        }, 
        // 压缩图片 
        compress(img) { 
            let canvas = document.createElement("canvas"); 
            let ctx = canvas.getContext("2d"); 
            let initSize = img.src.length; 
            let width = img.width; 
            let height = img.height; 
            canvas.width = width; 
            canvas.height = height; 
            // 铺底色 
            ctx.fillStyle = "#fff"; 
            ctx.fillRect(0, 0, canvas.width, canvas.height); 
            ctx.drawImage(img, 0, 0, width, height); 
            //进行最小压缩 
            let ndata = canvas.toDataURL("image/jpeg", 0.1); 
            console.log("压缩后的图片大小:" + ndata.length); 
            console.log("压缩后的图片内容:" + ndata)
            return ndata; 
        }, 
        // base64转成bolb对象 
        dataURItoBlob(base64Data) { 
            var byteString; 
            if (base64Data.split(",")[0].indexOf("base64") >= 0) 
                byteString = atob(base64Data.split(",")[1]); 
            else 
                byteString = unescape(base64Data.split(",")[1]); 
            var mimeString = base64Data .split(",")[0] .split(":")[1] .split(";")[0]; 
            var ia = new Uint8Array(byteString.length); 
            for (var i = 0; i < byteString.length; i++) { 
                ia[i] = byteString.charCodeAt(i); 
            } 
            return new Blob([ia], { type: mimeString }); 
        },
        //删除事件 
        delImg() { 
            this.src = null; 
        } 
    }
}
</script>
<style scoped lang="stylus" rel="stylesheet">
@import \'../../assets/stylus/index.styl\'
.tips{
    padding 10px
    line-height 1.5em
}
.el-form-item{
    margin-bottom 18px
    background-color #fff
}
.miForm /deep/ input{
    border none
}

.upload {
    margin-left 20px
    width 150px
    height 150px
    border:2px solid #ddd;
    border-radius: 2px;
    text-align: center;
    overflow:hidden
    position:relative;
    label{
        line-height 150px
        font-size: 30px;
    }
    .del{
        position:absolute;
        right:0;
        top:0;
        color:red;
    }
}
input[type=\'file\'] { 
    display: none; 
}
</style>