axios 实现上传、下载

发布于:2024-04-26 ⋅ 阅读:(16) ⋅ 点赞:(0)

 一、下载(支持批量下载)

  const downloadFile = (fileList) => {
    console.log(fileList, '下载list')
    fileList.forEach((e) => {
      const uid = uuidv4()
      const CancelToken = axios.CancelToken
      let source = CancelToken.source()
      transmissionStore().setDownloadSource('add', {
        workId: uid,
        axiosSource: source,
      })
      axios({
        url: `/xxxxxxxxx`,
        method: 'get',
        params: {
          id: uid,
          filePath: e.filePath,
          isDir: e.isDir,
        },
        responseType: 'blob',
        headers: {
          'Content-Type': 'application/json; charset=utf-8',
          workId: uid,
        },
        cancelToken: source.token,
        onDownloadProgress: function (progressEvent) {
          downloadLodashdebounce(uid, progressEvent) //节流推送
          if (progressEvent.total == progressEvent.loaded) {
            setTimeout(() => {
              transmissionStore().setDownloadSource('delete', {
                workId: uid,
              })
            }, 1000)
          }
        },
      })
        .then((res) => {
          const blob = new Blob([res.data], {
            type: 'application/octet-stream',
          })
          const url = window.URL.createObjectURL(blob)
          const a = document.createElement('a')
          a.href = url
          a.download = e.isDir ? `${e.fileName}.zip` : e.fileName
          document.body.appendChild(a)
          a.click()
          document.body.removeChild(a)
          window.URL.revokeObjectURL(url)
        })
        .catch((error) => {
          console.log(error, '下载接口中断')
        })
    })
    proxy.$message({
      message: '已添加至传输列表',
      type: 'success',
    })
  }




// 中断接口下载
source.cancel(`取消下载`)

二、上传(支持批量上传)

  const uploadFile = (e, is_file) => {
    const path = info.filePathList.join('/')
    const pathValue = path ? `${userData.value.username}/` + path : ''
    let file_lists = Object.values(e.target.files)
    console.log(file_lists, '上传list')
    if (file_lists.length > 0 && file_lists.length <= 30) {
      file_lists.forEach((item) => {
        const uid = uuidv4()
        const formData = new FormData()
        formData.append('fileName', item.name)
        formData.append('file', item)
        formData.append('filePath', pathValue)
        if (!is_file) {
          let folderName = item.webkitRelativePath.split('/')
          folderName.pop()
          formData.append('dirName', folderName.join('/'))
        }

        const CancelToken = axios.CancelToken
        let source = CancelToken.source()
        transmissionStore().setUploadSource('add', {
          workId: uid,
          axiosSource: source,
        })
        axios({
          url: `/xxxxx/upload`,
          method: 'post',
          data: formData,
          headers: {
            workId: uid,
          },
          cancelToken: source.token,
          onUploadProgress: function (progressEvent) {
            lodashdebounce(uid, progressEvent, formData) //节流推送
            if (progressEvent.total == progressEvent.loaded) {
              setTimeout(() => {
                transmissionStore().setUploadSource('delete', {
                  workId: uid,
                })
              }, 1000)
            }
          },
        })
          .then((res) => {})
          .catch((error) => {
            console.log(error, '上传接口中断')
            transmissionStore().setOperationObj({
              type: 'filecancel',
              data: {
                id: uid,
                fileName: formData.get('fileName'),
              },
            })
          })
      })
      nextTick(() => {
        file_ref.value.value = null
        folder_ref.value.value = null
      })
      proxy.$message({
        message: '已添加至传输列表',
        type: 'success',
      })
    } else {
      proxy.$message({
        message: '文件数量超过限制,最多可上传30个。',
        type: 'warning',
      })
      nextTick(() => {
        file_ref.value.value = null
        folder_ref.value.value = null
      })
    }
  }



// 中断接口上传
source.cancel(`取消上传`)