記錄做分片上傳文件(SparkMD5)

一、為什么要使用分片上傳

要用分片上傳,首先要知道為什么要使用分片上傳,或者說那些場景下要使用分片上傳。

    1.文件過大:一個文件過大,幾個G或者幾十G的大文件就非常適合分片上傳

    2.網(wǎng)絡不穩(wěn)定:網(wǎng)絡時好時壞或者比較慢的情況

    3.斷點續(xù)傳:傳了一部分后暫停想繼續(xù)傳的時候,分片上傳也是個不錯的選擇(斷點續(xù)傳需要考慮其他因素,這里不做具體詳情的講說)

二、安裝spark-md5

npm i spark-md5

三、實現(xiàn)方法

import SparkMD5 from 'spark-md5'
import mofangAi from '@/lib/mofangAi.js'
import $ from 'jquery'
import store from '@/store/index'

// 分片大小 5m
const chunkSize = 5 * 1024 * 1024
// 允許上傳的文件類型
const allowType = [
  'image/jpg',
  'image/png'
]

/**
 * 壓縮圖片
 *@param img 被壓縮的img對象
 * @param type 壓縮后轉換的文件類型
 * @param mx 觸發(fā)壓縮的圖片最大寬度限制
 * @param mh 觸發(fā)壓縮的圖片最大高度限制
 */
export function compressImg (img, type, mx, mh) {
  return new Promise((resolve) => {
    const canvas = document.createElement('canvas')
    const context = canvas.getContext('2d')
    const { width: originWidth, height: originHeight } = img
    // 最大尺寸限制
    const maxWidth = mx
    const maxHeight = mh
    // 目標尺寸
    let targetWidth = originWidth
    let targetHeight = originHeight
    if (originWidth > maxWidth || originHeight > maxHeight) {
      if (originWidth / originHeight > 1) {
        // 寬圖片
        targetWidth = maxWidth
        targetHeight = Math.round(maxWidth * (originHeight / originWidth))
      } else {
        // 高圖片
        targetHeight = maxHeight
        targetWidth = Math.round(maxHeight * (originWidth / originHeight))
      }
    }
    canvas.width = targetWidth
    canvas.height = targetHeight
    context.clearRect(0, 0, targetWidth, targetHeight)
    // 圖片繪制
    context.drawImage(img, 0, 0, targetWidth, targetHeight)
    canvas.toBlob(function (blob) {
      resolve(blob)
    }, type || 'image/png')
  })
}

// 壓縮前將file轉換成img對象
function readImg (file) {
  return new Promise((resolve, reject) => {
    const img = new Image()
    const reader = new FileReader()
    reader.onload = function (e) {
      img.src = e.target.result
    }
    reader.onerror = function (e) {
      reject(e)
    }
    reader.readAsDataURL(file)
    img.onload = function () {
      resolve(img)
    }
    img.onerror = function (e) {
      reject(e)
    }
  })
}

// 批量上傳圖片(選擇+拖拽)
export const newUploadFile = async (
  fileList, type
) => {
  for (var i = 0; i < fileList.length; i++) {
    await uploadFile(
      fileList[i], type
    )
  }
}

export const uploadFile = async (
  file, type
) => {
  // 限制上傳文件類型
  const arr = file.name.split('.')
  const fileType = arr[arr.length - 1].toLowerCase()
  const fileSize = file.size
  try {
    if (
      fileSize > 15 * 1024 * 1024 &&
      ['png', 'jpg', 'jpeg'].includes(fileType)
    ) {
      const img = await readImg(file)
      const blob = await compressImg(img, file.type, 660, 432)
      const formData = new FormData()
      formData.append('file', blob, file.name)
    }
  } catch (error) {
    console.log('error', error)
  }
  if (!allowType.includes('.' + fileType)) {
    console.log(`暫不支持上傳` + fileType + '格式文件')
    return
  }

  let startTime = new Date().getTime()
  let percent = 0

  // 計算當前選擇文件需要的分片數(shù)量
  let chunkCount = Math.ceil(fileSize / chunkSize)
  if (fileSize > chunkSize) {
    chunkCount--
  }

  // 獲取文件md5
  const fileMd5 = await getFileMd5(file)

  // 向后端請求本次分片上傳初始化
  const initUploadParams = {
    chunkCount: chunkCount,
    fileMd5: fileMd5,
    fileName: file.name
  }
  try {
    const res = await mofangAi.initChunk(initUploadParams)
    if (res.status === 0) {
      // 上傳成功了
      changeProgress(100, startTime, fileSize, type)
      updataSuccess(res.minioOutput.fileName, type)
      return
    }
    if (res.status === 2) {
      // 上傳完成,需要合并
      changeProgress(100, startTime, fileSize, type)
      composeFile(fileMd5, file)
      return
    }

    const chunkUploadUrls = res.minioOutputs
    for (let item of chunkUploadUrls) {
      // 分片開始位置
      let start = (item.partNumber - 1) * chunkSize
      // 分片結束位置
      let end = Math.min(fileSize, start + chunkSize)
      if (item.partNumber === chunkCount) {
        end += chunkSize
      }
      // 取文件指定范圍內的byte,從而得到分片數(shù)據(jù)
      let _chunkFile = file.slice(start, end)
      await $.ajax({
        url: item.uploadUrl,
        type: 'PUT',
        contentType: false,
        processData: false,
        data: _chunkFile,
        xhr: xhrOnProgress(function (evt) {
          // 計算百分比
          percent = Math.floor(
            ((chunkSize * (item.partNumber - 1) + evt.loaded) / file.size) * 100
          )
          changeProgress(
            percent,
            startTime,
            fileSize,
            type
          )
        }),
        success: function () { },
        error: function () {
          console.log('上傳失敗')
        }
      })
    }
    composeFile(fileMd5, file, type)
  } catch (error) {
    console.log('上傳失敗')
  }
}
/**
 * 請求后端合并文件
 * @param fileMd5
 * @param file
 */
const composeFile = (
  fileMd5,
  file,
  type
) => {
  const composeParams = {
    fileMd5: fileMd5,
    fileName: file.name
  }
  mofangAi.composeFile(composeParams).then((res) => {
    updataSuccess(res.fileName, type)
  })
}

/**
 * 獲取文件MD5
 * @param file
 * @returns {Promise<unknown>}
 */
const getFileMd5 = (file) => {
  var fileReader = new FileReader()
  var blobSlice = File.prototype.mozSlice || File.prototype.webkitSlice || File.prototype.slice
  var chunkSize1 = 102400
  var chunks = Math.ceil(file.size / chunkSize1)
  var currentChunk = 0
  var spark = new SparkMD5()
  return new Promise((resolve) => {
    fileReader.onload = function (e) {
      spark.appendBinary(e.target.result) // append binary string
      currentChunk++
      if (currentChunk < chunks) {
        loadNext()
      } else {
        resolve(spark.end())
      }
    }
    fileReader.onerror = () => {
      // ElMessage.error({
      //   message: '文件讀取失敗,無法上傳該文件',
      //   duration: 1000
      // })
      console.log('文件讀取失敗,無法上傳該文件')
      const body = document.querySelector('body')
      const uploadStatus = document.getElementById('upload-status')
      body.removeChild(uploadStatus)
    }

    function loadNext () {
      var start = currentChunk * chunkSize1
      var end = start + chunkSize1 >= file.size ? file.size : start + chunkSize1
      fileReader.readAsBinaryString(blobSlice.call(file, start, end))
    }

    loadNext()
  })
}

// 分片成功的回調
const xhrOnProgress = function (fun) {
  xhrOnProgress.onprogress = fun // 綁定監(jiān)聽
  // 使用閉包實現(xiàn)監(jiān)聽綁
  return function () {
    // 通過$.ajaxSettings.xhr();獲得XMLHttpRequest對象
    var xhr = $.ajaxSettings.xhr()
    // 判斷監(jiān)聽函數(shù)是否為函數(shù)
    if (typeof xhrOnProgress.onprogress !== 'function') return xhr
    // 如果有監(jiān)聽函數(shù)并且xhr對象支持綁定時就把監(jiān)聽函數(shù)綁定上去
    if (xhrOnProgress.onprogress && xhr.upload) {
      xhr.upload.onprogress = xhrOnProgress.onprogress
    }
    return xhr
  }
}

// 上傳成功回調
const updataSuccess = function (name, type) {
  let updataSuccessData = {
    name: name,
    type: type
  }
  store.commit('setName', updataSuccessData)
}

// 上傳進度更新
const changeProgress = function (
  percent,
  startTime,
  fileSize,
  type
) {
  let nowTime = new Date().getTime()
  console.log('上傳進度' + parseInt(percent) + '%')
  console.log('上傳時間' + secondsFormat(nowTime - startTime))
  console.log('上傳文件剩余大小' + sizeFormat((fileSize * percent) / 100) + '/' + sizeFormat(fileSize))
}

// 計算剩余時間
const secondsFormat = function (ms) {
  var s = Math.floor(ms / 1000)
  var day = Math.floor(s / (24 * 3600))
  var hour = Math.floor((s - day * 24 * 3600) / 3600)
  var minute = Math.floor((s - day * 24 * 3600 - hour * 3600) / 60)
  var second = s - day * 24 * 3600 - hour * 3600 - minute * 60
  let str = ''
  if (day) {
    str += day + ':'
  }
  str =
    str +
    (hour > 9 ? hour : '0' + hour) +
    ':' +
    (minute > 9 ? minute : '0' + minute) +
    ':' +
    (second > 9 ? second : '0' + second)
  return str
}

// 計算剩余大小
const sizeFormat = function (limit) {
  var size = ''
  if (limit < 1 * 1024) {
    size = limit.toFixed(2) + 'B'
  } else if (limit < 1 * 1024 * 1024) {
    size = (limit / 1024).toFixed(2) + 'KB'
  } else if (limit < 1 * 1024 * 1024 * 1024) {
    size = (limit / (1024 * 1024)).toFixed(2) + 'MB'
  } else {
    size = (limit / (1024 * 1024 * 1024)).toFixed(2) + 'GB'
  }
  var sizeStr = size + ''
  var index = sizeStr.indexOf('.')
  var dou = sizeStr.substr(index + 1, 2)
  if (dou === '00') {
    return sizeStr.substring(0, index) + sizeStr.substr(index + 3, 2)
  }
  return size
}

?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容