Vue上傳全解析

一、Vue上傳文件

VUE是一個簡約的面向數據的用戶界面庫,它也是一個非常好的前端框架,它提供了很多 UI 組件和插件來幫助我們快速開發應用程序。Vue上傳文件主要使用 input 標籤和file類型,需要注意的是,input 標籤的 type屬性必須是 “file”,而且必須要有 @change事件監聽。

<template>
  <div>
    <input type="file" @change="uploadFile" />
  </div>
</template>

<script>
  export default {
    methods: {
      uploadFile(event) {
        const file = event.target.files[0];
        console.log(file);
      }
    }
  }
</script>

二、Vue上傳本地文件存到緩存里

文件一般需要上傳到服務器,為了減少上傳時間,可以先將文件存到緩存里,在上傳時再將緩存里的文件一併上傳。在VUE中,可以使用 FileReader 對象將上傳文件保存到瀏覽器緩存。

<template>
  <div>
    <input type="file" @change="readFile" />
  </div>
</template>

<script>
  export default {
    methods: {
      readFile(event) {
        const file = event.target.files[0];
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => {
          const fileContent = reader.result;
          localStorage.setItem('fileName', fileContent);
        }
      }
    }
  }
</script>

三、Vue上傳文件後展示

上傳文件後,需要將文件展示出來。在VUE中,可以使用URL.createObjectURL()將文件轉換成URL形式,然後將URL顯示在頁面上。

<template>
  <div>
    <input type="file" @change="showFile" />
    <img :src="fileUrl" />
  </div>
</template>

<script>
  export default {
    data() {
      return {
        fileUrl: ''
      }
    },
    methods: {
      showFile(event) {
        const file = event.target.files[0];
        const fileUrl = URL.createObjectURL(file);
        this.fileUrl = fileUrl;
      }
    }
  }
</script>

四、Vue上傳固定格式文件

為了保證後端的正確解析,可能需要上傳固定格式的文件。在VUE中,可以使用accept屬性限制上傳的文件類型。

<template>
  <div>
    <input type="file" accept=".txt" @change="uploadFile" />
  </div>
</template>

<script>
  export default {
    methods: {
      uploadFile(event) {
        const file = event.target.files[0];
        console.log(file);
      }
    }
  }
</script>

五、Vue上傳頭像

上傳頭像時,需要對上傳圖片進行裁剪和壓縮。在VUE中,可以使用vue-cropper插件、vue-photo-preview插件或者原生canvas進行裁剪和壓縮。下面是使用vue-cropper插件進行頭像上傳的示例代碼。

<template>
  <div>
    <vue-cropper
      ref="cropper"
      :guides="false"
      :view-mode="2"
      :auto-crop-area="0.8"
      :background="false"
    />
    <button @click="uploadAvatar">上傳頭像</button>
  </div>
</template>

<script>
  import VueCropper from 'vue-cropperjs';
  import 'cropperjs/dist/cropper.css';

  export default {
    components: { VueCropper },
    methods: {
      uploadAvatar() {
        const cropper = this.$refs.cropper.$cropper;
        cropper.getCroppedCanvas().toBlob(blob => {
          console.log(blob);
        });
      }
    }
  }
</script>

六、Vue上傳功能

很多應用都需要上傳文件,比如上傳圖片、上傳附件等。在VUE中,可以使用axios、fetch等網絡請求庫實現上傳功能。下面是使用axios實現上傳的示例代碼。

<template>
  <div>
    <input type="file" @change="uploadFile" />
    <button @click="handleSubmit">上傳</button>
  </div>
</template>

<script>
  import axios from 'axios';
  
  export default {
    data() {
      return {
        file: null,
        formData: new FormData()
      }
    },
    methods: {
      uploadFile(event) {
        this.file = event.target.files[0];
        this.formData.append('file', this.file);
      },
      handleSubmit() {
        axios.post('/upload', this.formData)
          .then(response => {
            console.log(response);
          })
          .catch(error => {
            console.log(error);
          });
      }
    }
  }
</script>

七、Vue上傳文件到後端

將文件上傳到後端需要使用ajax或者form表單提交,一般使用ajax。在VUE中,可以使用axios、fetch等網絡請求庫實現上傳文件到後端。下面是使用axios實現上傳文件到後端的示例代碼。

<template>
  <div>
    <input type="file" @change="uploadFile" />
    <button @click="handleSubmit">上傳</button>
  </div>
</template>

<script>
  import axios from 'axios';

  export default {
    data() {
      return {
        file: null,
        formData: new FormData()
      }
    },
    methods: {
      uploadFile(event) {
        this.file = event.target.files[0];
        this.formData.append('file', this.file);
      },
      handleSubmit() {
        axios.post('/upload', this.formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        })
        .then(response => {
          console.log(response);
        })
        .catch(error => {
          console.log(error);
        });
      }
    }
  }
</script>

八、Vue上傳圖片

上傳圖片可以選擇上傳到服務器或者上傳到第三方雲存儲。在VUE中,可以使用axios、fetch等網絡請求庫實現上傳圖片。下面是使用axios實現上傳圖片的示例代碼。

<template>
  <div>
    <input type="file" accept="image/*" @change="uploadImg" />
    <button @click="handleSubmit">上傳</button>
  </div>
</template>

<script>
  import axios from 'axios';

  export default {
    data() {
      return {
        img: null,
        formData: new FormData()
      }
    },
    methods: {
      uploadImg(event) {
        this.img = event.target.files[0];
        this.formData.append('img', this.img);
      },
      handleSubmit() {
        axios.post('/upload', this.formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        })
        .then(response => {
          console.log(response);
        })
        .catch(error => {
          console.log(error);
        });
      }
    }
  }
</script>

九、Vue上傳txt文件

上傳txt文件時,需要對上傳的文件進行處理(如編碼轉換等)。在VUE中,可以使用FileReader對象讀取文件內容,並進行處理。下面是一個上傳txt文件並讀取文件內容的示例代碼。

<template>
  <div>
    <input type="file" accept=".txt" @change="uploadTxt" />
    <button @click="handleSubmit">上傳</button>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        txt: null,
        formData: new FormData()
      }
    },
    methods: {
      uploadTxt(event) {
        this.txt = event.target.files[0];
        const reader = new FileReader();
        reader.readAsText(this.txt);
        reader.onload = () => {
          this.formData.append('txt', reader.result);
        };
      },
      handleSubmit() {
        // 同八中的axios上傳方式一致,這裡不進行重複展示。
        console.log(this.formData);
      }
    }
  }
</script>

十、Vue上傳文件進度條

對於大文件上傳的操作,需要有進度條來提示用戶上傳的進度。在VUE中,可以使用axios的onUploadProgress事件實現上傳進度條。下面是一個上傳進度條的示例代碼。

<template>
  <div>
    <input type="file" @change="uploadFile" />
    <button @click="handleSubmit">上傳</button>
    <div class="progress">
      <div class="progress-bar" :style="{ width: uploadProgress + '%'}">
        {{ uploadProgress }}%
      </div>
    </div>
  </div>
</template>

<script>
  import axios from 'axios';

  export default {
    data() {
      return {
        file: null,
        formData: new FormData(),
        uploadProgress: 0
      }
    },
    methods: {
      uploadFile(event) {
        this.file = event.target.files[0];
        this.formData.append('file', this.file);
      },
      handleSubmit() {
        axios.post('/upload', this.formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          },
          onUploadProgress: progressEvent => {
            this.uploadProgress = Math.round(
              (progressEvent.loaded * 100) / progressEvent.total
            )
          }
        })
        .then(response => {
          console.log(response);
        })
        .catch(error => {
          console.log(error);
        });

        this.uploadProgress = 0;
      }
    }
  }
</script>

原創文章,作者:UAJXK,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/368968.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
UAJXK的頭像UAJXK
上一篇 2025-04-12 13:00
下一篇 2025-04-12 13:00

相關推薦

  • 使用Vue實現前端AES加密並輸出為十六進制的方法

    在前端開發中,數據傳輸的安全性問題十分重要,其中一種保護數據安全的方式是加密。本文將會介紹如何使用Vue框架實現前端AES加密並將加密結果輸出為十六進制。 一、AES加密介紹 AE…

    編程 2025-04-29
  • Vue TS工程結構用法介紹

    在本篇文章中,我們將從多個方面對Vue TS工程結構進行詳細的闡述,涵蓋文件結構、路由配置、組件間通訊、狀態管理等內容,並給出對應的代碼示例。 一、文件結構 一個好的文件結構可以極…

    編程 2025-04-29
  • 百度網盤Python上傳

    百度網盤是一個常用的雲存儲平台,提供了多種上傳文件的方式,其中包括使用Python進行上傳。本文將從安裝Python、安裝依賴庫、上傳文件三個方面進行詳細闡述。 一、安裝Pytho…

    編程 2025-04-28
  • 如何使用git拉出某個用戶上傳的文件?

    Git是一個非常流行的版本控制系統,它可以幫助團隊協作,並保證代碼的版本控制。有時候,我們需要拉出某個用戶上傳的文件,但不知道從哪裡開始。本文將會從多個方面詳細闡述如何使用git拉…

    編程 2025-04-28
  • 上傳多媒體文件的常用方法——uploadmediabyurl

    uploadmediabyurl是一個非常常用的方法,它允許我們將本地的多媒體文件上傳到微信服務器上。 一、uploadmediabyurl的基本使用方法 要使用uploadmed…

    編程 2025-04-27
  • Vue3的vue-resource使用教程

    本文將從以下幾個方面詳細闡述Vue3如何使用vue-resource。 一、安裝Vue3和vue-resource 在使用vue-resource前,我們需要先安裝Vue3和vue…

    編程 2025-04-27
  • NB設備上傳數據方案

    NB(Narrow Band)是一種物聯網通信技術,可以實現低功耗、寬覆蓋、多連接等特點。本文旨在探討如何使用NB設備上傳數據。在這篇文章中,我們將介紹NB設備上傳數據的基本原理、…

    編程 2025-04-27
  • Vue模擬按鍵按下

    本文將從以下幾個方面對Vue模擬按鍵按下進行詳細闡述: 一、Vue 模擬按鍵按下的場景 在前端開發中,我們常常需要模擬按鍵按下的場景,比如在表單中填寫內容後,按下「回車鍵」提交表單…

    編程 2025-04-27
  • ThinkPHP6 + Vue.js: 不使用Fetch的數據請求方法

    本文將介紹如何在ThinkPHP6和Vue.js中進行數據請求,同時避免使用Fetch函數。 一、AJAX:XMLHttpRequest的基礎使用 在進行數據請求時,最基礎的方式就…

    編程 2025-04-27
  • 開發前端程序,Vue是否足夠?

    Vue是一個輕量級,高效,漸進式的JavaScript框架,用於構建Web界面。開發人員可以使用Vue輕鬆完成前端編程,開發響應式應用程序。然而,當涉及到需要更大的生態系統,或利用…

    編程 2025-04-27

發表回復

登錄後才能評論