element Manually upload base64 encoded pictures Preview pictures Download pictures Delete pictures

Article directory

  • scenes to be used
  • page effect
  • front-end code
  • Reference book

Usage scenario

vue2 + element can manually upload base64 encoded pictures, preview pictures, download pictures, and delete pictures.
After the browser selects the local image, the front-end program converts the image into base64 encoding. Click the “Save” button to submit the base64 encoding of the image to the server.

Page Effect

page effect

Front-end code

file hetong.vue. Note, please use the variable info according to the data in the actual project.

<template>
    <div id="create" class="create" style="overflow-y: auto; position: relative; height: 100%;">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="130px">
            <el-form-item label="Contract">
                <el-upload multiple
                           list-type="picture-card"
                           action=""
                           :auto-upload="false"
                           :on-change="handleChange"
                           :file-list="fileList"
                           :on-exceed="handleExceed"
                           accept=".jpg,.png,.jpeg,.gif"
                           :before-upload="onBeforeUpload">
                    <i slot="default" class="el-icon-plus"></i>
                    <div slot="file" slot-scope="{file}">
                        <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
                        <span class="el-upload-list__item-actions">
                            <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                                <i class="el-icon-zoom-in"></i>
                            </span>
                            <span class="el-upload-list__item-delete" @click="handleDownload(file)">
                                <i class="el-icon-download"></i>
                            </span>
                            <span class="el-upload-list__item-delete" @click="handleRemove(file)">
                              <i class="el-icon-delete"></i>
                            </span>
                        </span>
                    </div>
                </el-upload>
                <div style="font-size: 12px;color: #8c939d">
                    <i class="el-icon-warning-outline"></i>
                    <span>Only upload pictures in jpg, png, jpeg, gif format, and no more than 5M</span>
                </div>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitForm('ruleForm')">Save</el-button>
            </el-form-item>
        </el-form>
        <!--Preview image-->
        <el-dialog :visible.sync="dialogVisible" append-to-body>
            <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
    </div>
</template>

<script>
module.exports = {<!-- -->
    name: "renyuan_hetong",
    props: {<!-- -->
        info:Object //Note, please use the variable info according to the data in the actual project
    },
    data: function () {<!-- -->
        return {<!-- -->
            dialogImageUrl: '',
            dialogVisible: false,

            fileList: [],
            fileListBase: {<!-- -->},//store image base64 encoding
            ruleForm: {<!-- -->
                contract: []
            },
            rules: {<!-- -->},
        }
    },
    created: function () {<!-- -->
        console.log('renyuan_hetong created');
    },
    methods: {<!-- -->
        // check before upload
        onBeforeUpload: function (file) {<!-- -->
            const isJPG =
                    file.type === 'image/jpg' || file.type === 'image/png' || file.type === 'image/jpeg' || file.type === 'image/gif' ;
            const isLt2M = file. size / 1024 / 1024 < 5;
            if (!isJPG) {<!-- -->
                this.$message.error('Upload pictures can only be in JPG, PNG, JPEG, GIF format!');
            }
            if (!isLt2M) {<!-- -->
                this.$message.error('Upload image size cannot exceed 2MB!');
            }
            return isJPG & & isLt2M;
        },
        // check number
        handleExceed(files, fileList) {<!-- -->
            this.$message.warning('Please delete the picture before re-uploading');
        },
        // delete image
        handleRemove(file) {<!-- -->
            let findIndex = -1;
            let findK = -1;
            for (let index in this.fileList) {<!-- -->
                let item = this. fileList[index];
                if (item.uid == file.uid) {<!-- -->
                    findIndex = index;
                    findK = file.uid;
                    break;
                }
            }
            if (findIndex > -1) {<!-- -->
                this.fileList.splice(findIndex, 1);
            }
            if (findK > -1) {<!-- -->
                delete this.fileListBase[findK];
            }
        },
        handlePictureCardPreview(file) {<!-- -->
            this.dialogImageUrl = file.url;
            this.dialogVisible = true;
        },
        handleDownload(file) {<!-- -->
            let name = this.info.staff.name + '_Contract_' + this.info.company.name;
            let imgsrc = file.url;
            let image = new Image();
            // Solve the problem of cross-domain Canvas pollution
            image.setAttribute("crossOrigin", "anonymous");
            image.src = imgsrc;
            image.onload = function() {<!-- -->
                let canvas = document. createElement("canvas");
                canvas.width = image.width;
                canvas.height = image.height;
                let context = canvas. getContext("2d");
                context. drawImage(image, 0, 0, image. width, image. height);
                let url = canvas.toDataURL("image/png"); //Get the base64 encoded data of the image
                let a = document.createElement("a"); // generate an a element
                let event = new MouseEvent("click"); // create a click event
                a.download = name || "photo"; // set the picture name
                a.href = url; // Set the generated URL to the a.href attribute
                a.dispatchEvent(event); // Trigger the click event of a
            }
        },
        // Triggered when uploading
        handleChange(file, fileList) {<!-- -->
            let _this = this;

            _this.fileToBase64(file.raw, function (res) {<!-- -->
                let k = file.uid;
                _this.fileListBase[k] = res.target.result;
            });

            this.fileList = fileList;
        },
        fileToBase64(file, callback) {<!-- -->
            const fileReader = new FileReader()
            fileReader. readAsDataURL(file)
            fileReader.onload = function (result) {<!-- -->
                callback(result)
            }
        },
        submitForm(formName) {<!-- -->
            let _this = this, params = this. $data[formName];

            params.staff_id = this.info ? this.info.staff_id : null;
            params.id = this.info ? this.info.id : null;

            params. contract = [];
            for (let file of this. fileList) {<!-- -->
                if (!file.raw) {<!-- -->
                    params.contract.push(file.url);
                } else {<!-- -->
                    let k = file.uid;
                    params.contract.push(_this.fileListBase[k]);
                }
            }

            if (!params. contract) {<!-- -->
                _this.$message.error('The contract has not changed');
                return false;
            }
            if (!this.info) {<!-- -->
                _this.$message.error('There is no record, the contract cannot be uploaded');
                return false;
            }

            this.$refs[formName].validate((valid) => {<!-- -->
                if (valid) {<!-- -->
                    httpPost('m=zhuchang & amp;c=upContract', params).then(function (response) {<!-- -->
                        let res = response.data;
                        if (res. error == 0) {<!-- -->
                            _this.$message.success(res.msg);
                            _this.fileList = [];
                            for (let item of res. data) {<!-- -->
                                _this.fileList.push({<!-- -->name: 'contract', url: item});
                            }
                            _this.$emit("change-hetong");
                        } else {<!-- -->
                            _this.$message.error(res.msg);
                        }
                    });
                } else {<!-- -->
                    return false;
                }
            });
        }
    },
    watch: {<!-- -->
        info: {<!-- -->
            handler: function (val, oldVal) {<!-- -->
                console.log('renyuan_hetong watch info', val);
                //do...
                if (val.id & amp; & val.staff_id) {<!-- -->
                    this.fileListBase = {<!-- -->};
                    //display the existing image
                    this.fileList = [];
                    for(let item of val. contract_n){<!-- -->
                        this.fileList.push({<!-- -->name: 'contract', url: item});
                    }
                }
            },
            deep: true,
            immediate: true
        }
    }
}
</script>

<style scoped>
.el-upload-list--picture-card .el-upload-list__item-actions span + span{<!-- -->
    margin-left: 10px;
}
</style>

Reference Manual

  1. Element official website, Upload https://element.eleme.cn/#/zh-CN/component/upload