1. 程式人生 > >vue+axios+vuetify 執行圖片上傳及預覽功能

vue+axios+vuetify 執行圖片上傳及預覽功能

上傳前
在這裡插入圖片描述
上傳後
在這裡插入圖片描述
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); }) } },