Use of Upload component in Element-UI

(I wrote CSDN for the first time, sorry for the bad writing!)

1. We can check the related parameter configuration of Upload on the official website of Element, but I think many people don't know the implementation principle of action, and I don't know either. But we also want to use the Element-UI Upload component to upload images, what should we do? I have also read a lot of articles, let me talk about my understanding and solutions, welcome to discuss.

<el-upload class="upload-demo" drag multiple action="#" 
    :http-request="Upload_file" 
    :before-upload="beforeUpload"
    >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
            将文件拖到此处,或
            <em>点击上传</em>
        </div>
        <template #tip>
            <div class="el-upload__tip">
                只能上传 jpg/png 文件,且不超过 500kb
            </div>
        </template>
</el-upload>

2. The above code directly copies the Upload component, and configures action='#'; (http-request: overrides the default upload behavior, and can customize the upload implementation, so we don't need to configure this action address here)

3. In this component, we have configured two attributes: before-upload and http-request, the functions are:

        3.1 before-upload: Do some checks before uploading, such as file type, file size, and can receive file parameters. I believe everyone should be able to understand the output file.

        3.2 http-request: This is our code for processing uploaded files. When we obtain the image information uploaded by users, we must save it in the database, so we must use the base64 type of file.

/* 自定义上传文件 */
function Upload_file(data){       // data是上传的文件信息,里面有我们想要的file属性
    let reader = new FileReader() // 创建文件读取对象
    let file = data.file
    reader.readAsDataURL(file) // 文件读取转换为base64类型
    reader.onloadend = function (e) {
        console.log(e.target.result);
    }
}

4. The console outputs the base64 file data:

 5. After getting this data, I don’t need to talk about the rest. It’s time to check and check. The text format is used to save the database, and we can get the data by ourselves through the Upload component.

Tips: If there is anything wrong, please correct me~

Guess you like

Origin blog.csdn.net/weixin_47746452/article/details/121100698