前端大文件分片上傳(Vue)

list.vue

<template>
  <el-button
    type="primary"
    :disabled="disabled || isDisabled"
    :loading="buttonLoading"
    @click="confirm()"
    >{{ buttonLoading ? percentage + "%" : title }}</el-button
  >
</template>

<script>
import { uploadByPieces } from "./comUpload";
export default {
  props: {
    title: {
      type: String,
      default: "保存",
    },
    disabled: {
      type: Boolean,
      default: true,
    },
    uploadSuccess: {
      type: Boolean,
      default: true,
    },
    selectFile: {
      type: Object,
      default: () => {},
    },
    url: {
      type: Function,
      default: null,
    },
    // 數(shù)據(jù)校驗
    checkMsg: {
      type: Function,
      default: null,
    },
    // 數(shù)據(jù)保存
    submitMsg: {
      type: Function,
      default: null,
    },
    submitMsgStep: {
      type: Function,
      default: null,
    },
  },
  data() {
    return {
      buttonLoading: false,
      isDisabled: false,
      percentage: 0,
    };
  },
  created() {},
  watch: {
    uploadSuccess: {
      handler(val) {
        if (val) {
          this.buttonLoading = false;
          this.isDisabled = false;
        }
      },
      deep: true, // 深度監(jiān)聽
      immediate: true, // 初次監(jiān)聽即執(zhí)行
    },
  },
  mounted() {},
  methods: {
   async confirm() {
      if (this.checkMsg && !await this.checkMsg()) {
        return false;
      }
      this.buttonLoading = true;
      this.isDisabled = true;
      const _self = this;
      const maxSize = 200 * 1024 * 1024;
      //大于200M文件使用分片上傳
      if (this.selectFile.size >= maxSize) {
        this.upLoadData = this.selectFile.raw;
        // 分片上傳
        uploadByPieces({
          file: this.upLoadData, // 文件實體
          pieceSize: 20, // 分片大小
          baseURL: this.url,   //接口地址
          selectedSize: 1024, // 用于抽取文件首尾各多少字節(jié)作為md5值
          success:async (response) => {
            this.percentage = 100;
            if (response.chunk === response.chunkCount) {
              this.$emit("uploadComplete", response);
              if (await this.submitMsg(response.filePath, response.chunkFileName)) {
                this.buttonLoading = false;
                this.isDisabled = false;
              } else {
                this.buttonLoading = false;
                this.isDisabled = false;
              }
            }
          },
          uploading: (res) => {
            //分片傳輸中
            this.percentage = parseInt((res.current / res.total) * 100);
          },
          error: (e) => {
            this.buttonLoading = false;
            this.isDisabled = false;
            this.$message({
              message: "上傳失斨壮啊腮鞍!",
              type: "success",
            });
          },
        });
      } else {
        this.submitMsgStep();
      }
    },
  },
};
</script>

comUpload.js

import SparkMD5 from 'spark-md5';
//文件分片處理
export const uploadByPieces = ({
    file,
    pieceSize = 1,
    baseURL,
    selectedSize,
    success,
    uploading,
    error
}) => {
    const randomNumber = Date.now() + String(Math.round(Math.random() * 1000000))  // 生成隨機數(shù)
    // 上傳過程中用到的變量
    const chunkSize = pieceSize * 1024 * 1024; // pieceSize:5 MB一片
    const chunkCount = Math.ceil(file.size / chunkSize); // 總片數(shù)
    let identifier = ''
    // 計算md5的值
    const countMd5 = async () => {
        return new Promise(function async(resolve, reject) {
            const fileReader = new FileReader()
            if (file.size > selectedSize) {
                // 文件字節(jié)大于分割字節(jié)
                const md5 = new SparkMD5();
                let index = 0;
                const loadFile = (start, end) => {
                    const slice = file.slice(start, end);
                    fileReader.readAsBinaryString(slice);
                }
                loadFile(0, selectedSize);
                fileReader.onload = e => {
                    md5.appendBinary(e.target.result);
                    if (index === 0) {
                        index += selectedSize;
                        loadFile(file.size - selectedSize, file.size);
                    } else {
                        resolve(md5.end())
                    }
                };
            } else {
                fileReader.readAsBinaryString(file);
                fileReader.onload = e => {
                    resolve(SparkMD5.hashBinary(e.target.result))
                }
            }
        })
    }
    // 獲取file分片
    const getChunkInfo = (file, currentChunk, chunkSize) => {
        let start = (currentChunk - 1) * chunkSize;
        let end = Math.min(file.size, start + chunkSize);
        let chunk = file.slice(start, end);
        return { start, end, chunk };
    };
    // 調(diào)用接口上傳文件分片
    const uploadChunk = chunkInfo => {
        let fetchForm = new FormData();
        fetchForm.append("taskId", randomNumber); //傳輸任務(wù)ID
        fetchForm.append("chunkNumber", chunkInfo.currentChunk);  //第幾分片
        fetchForm.append("chunkSize", chunkSize); //分塊的大小
        fetchForm.append("totalChunks", chunkInfo.chunkCount);   //分片總數(shù)
        fetchForm.append("identifier", identifier); // 文件唯一標(biāo)識 md5
        fetchForm.append("selectedSize", selectedSize); // 用于抽取文件首尾各多少字節(jié)作為md5值
        fetchForm.append("originalFileName", file.name); // 用于抽取文件首尾各多少字節(jié)作為md5值    
        fetchForm.append("file", chunkInfo.chunk);// 分塊文件傳輸對象
        baseURL(fetchForm).then((res) => {
            if (~~res.success) {
                if (chunkInfo.currentChunk < chunkInfo.chunkCount) {
                    const { chunk } = getChunkInfo(
                        file,
                        chunkInfo.currentChunk + 1,
                        chunkSize
                    );
                    uploadChunk({
                        chunk,
                        currentChunk: chunkInfo.currentChunk + 1,
                        chunkCount: chunkInfo.chunkCount
                    });
                    uploading && uploading({
                        current: chunkInfo.currentChunk,
                        total: chunkInfo.chunkCount
                    });
                } else {
                    // 當(dāng)總數(shù)大于等于分片個數(shù)的時候
                    if (chunkInfo.currentChunk >= chunkInfo.chunkCount - 1) {
                        res.chunk = chunkInfo.currentChunk;
                        res.chunkCount = chunkInfo.chunkCount;
                        success && success(res);
                    }
                }
            } else {
                error && error(res);
            }
        })
    };
    // 針對每個文件進(jìn)行chunk處理
    const readChunk = () => {
        // 針對單個文件進(jìn)行chunk上傳
        const { chunk } = getChunkInfo(file, 1, chunkSize);
        uploadChunk({ chunk, currentChunk: 1, chunkCount });
    };
    countMd5().then(function (result) {
        identifier = result
        readChunk(); // 開始執(zhí)行代碼
    })
};

前端git項目
后端git地址
鏈接地址

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末硼端,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子董虱,更是在濱河造成了極大的恐慌纺酸,老刑警劉巖躏碳,帶你破解...
    沈念sama閱讀 219,270評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件手蝎,死亡現(xiàn)場離奇詭異,居然都是意外死亡普气,警方通過查閱死者的電腦和手機谜疤,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,489評論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人夷磕,你說我怎么就攤上這事履肃。” “怎么了坐桩?”我有些...
    開封第一講書人閱讀 165,630評論 0 356
  • 文/不壞的土叔 我叫張陵尺棋,是天一觀的道長。 經(jīng)常有香客問我绵跷,道長膘螟,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,906評論 1 295
  • 正文 為了忘掉前任碾局,我火速辦了婚禮荆残,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘净当。我一直安慰自己内斯,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,928評論 6 392
  • 文/花漫 我一把揭開白布像啼。 她就那樣靜靜地躺著俘闯,像睡著了一般。 火紅的嫁衣襯著肌膚如雪忽冻。 梳的紋絲不亂的頭發(fā)上真朗,一...
    開封第一講書人閱讀 51,718評論 1 305
  • 那天,我揣著相機與錄音僧诚,去河邊找鬼遮婶。 笑死,一個胖子當(dāng)著我的面吹牛湖笨,可吹牛的內(nèi)容都是我干的蹭睡。 我是一名探鬼主播,決...
    沈念sama閱讀 40,442評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼赶么,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了脊串?” 一聲冷哼從身側(cè)響起辫呻,我...
    開封第一講書人閱讀 39,345評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎琼锋,沒想到半個月后放闺,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,802評論 1 317
  • 正文 獨居荒郊野嶺守林人離奇死亡缕坎,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,984評論 3 337
  • 正文 我和宋清朗相戀三年怖侦,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,117評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡匾寝,死狀恐怖搬葬,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情艳悔,我是刑警寧澤急凰,帶...
    沈念sama閱讀 35,810評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站猜年,受9級特大地震影響抡锈,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜乔外,卻給世界環(huán)境...
    茶點故事閱讀 41,462評論 3 331
  • 文/蒙蒙 一床三、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧杨幼,春花似錦撇簿、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,011評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至歹撒,卻和暖如春莲组,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背暖夭。 一陣腳步聲響...
    開封第一講書人閱讀 33,139評論 1 272
  • 我被黑心中介騙來泰國打工锹杈, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人迈着。 一個月前我還...
    沈念sama閱讀 48,377評論 3 373
  • 正文 我出身青樓竭望,卻偏偏與公主長得像,于是被迫代替她去往敵國和親裕菠。 傳聞我的和親對象是個殘疾皇子咬清,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,060評論 2 355

推薦閱讀更多精彩內(nèi)容