Vue本地上傳圖片

<template>
        <section>
            <div v-bind:style="{backgroundImage:'url(' + imageUrl + ')'}">
                <i v-if="imageUrl.length == 0" class="el-icon-plus avatar-uploader-icon"></i>
                <input @change="handleUploadImage" type="file" accept="image/jpeg,image/x-png,image/gif"/>
            </div>
        </section>
    </template>
    <script>
        methods: {
            handleUploadImage(e) {
                var file = e.target.files[0]
                var name = e.target.value
                var fileName = name.substring(name.lastIndexOf('.') + 1).toLowerCase()
                if (fileName !== 'jpg' && fileName !== 'jpeg' && fileName !== 'png' && fileName !== 'gif') {
                    this.$message.error('圖片格式錯誤')
                    return
                }
                const isLt2M = file.size / 1024 / 1024 < 10
                if (!isLt2M) {
                    this.$message.error('上傳圖片大小不能超過 10MB!')
                } else {
                    this.transformFileToFormData(file)
                }
            },
            transformFileToFormData(file) {
                try {
                    const formData = new FormData()
                    formData.append('file', file)
                     const _self = this
                    var reader = new FileReader()
                    reader.readAsDataURL(file)
                    reader.onload = function(e) {
                        // 圖片base64化
                        var newUrl = this.result
                        _self.imageUrl = newUrl
                    }
                    this.imgFile = formData
                } catch (e) {
                    console.log(e)
                }
            }
        }
    </script>
複製代碼
相關文章
相關標籤/搜索