vue+axios+vuetify 执行图片上传及预览功能

版权声明:未经同意,不得随意转载转载 https://blog.csdn.net/lucky541788/article/details/85109494

上传前
在这里插入图片描述
上传后
在这里插入图片描述
html

<v-img
        :src="photoSrc?photoSrc:`${baseUrl}images/photoFile.jpg`"
        aspect-ratio="0.8"
        v-if="change"
>
    <!-- 上传(这个按钮我设置了透明,美观一些) -->
    <!-- 切记事件触发用 @change,因为它才可以检测到文件选择是否成功了 -->
    <input
            type="file"
            class="photoFileIn my-0 py-0"
            @change="previewImg($event)"
            accept="image/*"
            v-if="change"
    >
</v-img>

部分 data

        data() {
            return {// 这里用到了 vuex
                name: this.$store.state.name,
                sex: this.$store.state.sex,
                phone: this.$store.state.phone,
                address: this.$store.state.address,
                img: this.$store.state.photo
            }
        }

js

            previewImg: function (e) {
                var files = e.target.files[0];
                var that = this;
                
                // 判断浏览器是否支持 FileReader
                if (!e || !window.FileReader) {
                    alert("您的设备不支持图片预览功能,如需该功能请升级您的设备!");
                    return;
                }
                let reader = new FileReader();
                
                // 这里是最关键的一步,转换就在这里
                if (files) {
                    reader.readAsDataURL(files); 
                }
                
                reader.onload = function () {
                    that.photoSrc = this.result
                };
                // 设置文件
                this.img = files;
            },
            conRev() {
                // 判断图片是否有上传,减轻后台工作量
                var photo = null;
                if (this.img === this.$store.state.photo) {
                    photo = false;
                } else {
                    photo = this.img
                }

                // 数据转换 FormData 形式
                var form = new FormData();
                form.append('name', this.name);
                form.append('phone', this.phone);
                form.append('sex', this.sex);
                form.append('photo', photo);
                form.append('user_address', this.address);

                //添加请求头
                let config = {
                    headers: {'Content-Type': 'multipart/form-data'}
                }; 

                // 发送请求
                if (this.$refs.person.validate()) {
                    this.$http.post('url', form, config)
                        .then(response => {
                            alert(response.data);
                        })
                }
            },

猜你喜欢

转载自blog.csdn.net/lucky541788/article/details/85109494