input實(shí)現(xiàn)拖拽文件上傳

  <input
       id="fileInput"
       type="file"
       @change="onSelectFileInputChange"
       @drag.stop
        @dragover.stop
        style="display: none;"
        :multiple="false" //設(shè)為true時可以同時上傳多個文件
         accept="image/png" //限制上傳的文件類型
         title=""
 / >
 mounted() {
    // 防止拖拽時容器奔潰,要阻止拖拽事件的默認(rèn)行為
    const dragArr = ['dragenter', 'dragover', 'drop']
    dragArr.forEach((name) => {
      document.addEventListener(name, (event) => {
        event.preventDefault()
      })
      this.$once('hook:beforeDestroy', () => {
        document.removeEventListener(name, (event) => {
          event.preventDefault()
        })
      })
    })
  },
    // 拖拽更新文檔
    onSelectFileInputChange(e) {
      const files = e?.target?.files
      if (!files.length) {
        return
      }
      const file = files[0]
      const path = e?.target
      this.getFileInfo(file)
    },

    // 分塊讀取文件,不然文件太大會讀取失敗
    readFileInChunks(file, callback) {
      const chunkSize = 2097152; // 2MB
      const fileSize = file.size;
      let offset = 0;
      const reader = new FileReader();
      reader.onload = function (e) {
        // 繼續(xù)讀取剩余部分
        offset += chunkSize;
        if (offset < fileSize) {
          reader.readAsDataURL(file.slice(offset, offset + chunkSize));
        } else {
          callback({ data: reader, error: false })
        }
      };

      reader.onerror = function () {
        callback({ data: null, error: true })
      };

      // 開始讀取第一塊
      reader.readAsDataURL(file.slice(offset, offset + chunkSize));
    },
  //獲取文件信息
   getFileInfo(file) {
      return new Promise(async (resolve) => {
        if (!file || !file.size || !file.name) {
          resolve(null)
          return
        }
        this.readFileInChunks(file, (result) => {
          if (result.error) {
            return
          }
          //獲取到文件的base64
          const content = result.data.result
        })
      })
    },

// 更改拖拽時的圖標(biāo)
#fileInput::file-selector-button {
  background-image: url('path_to_your_icon.png');
  background-size: contain;
  background-repeat: no-repeat;
  height: 30px; /* 設(shè)置按鈕的高度 */
  width: 100px; /* 設(shè)置按鈕的寬度 */
  border: 1px solid #999; /* 設(shè)置按鈕的邊框 */
  color: #333; /* 設(shè)置按鈕的文本顏色 */
  padding: 5px 10px; /* 設(shè)置按鈕內(nèi)的填充 */
}
 
#fileInput {
  /* 隱藏默認(rèn)的文件選擇控件 */
  position: absolute;
  clip: rect(0, 0, 0, 0);
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容