vue封装请求 获取上传文件进度及设置超时时间

效果图:
在这里插入图片描述

/utils/request.js

// 上传文件
export function uploadFile({
    
    url, data, timeout, callback}) {
    
    
  timeout ? service.defaults.timeout = timeout : ''
  return service.post(url, data, {
    
    
    headers: {
    
     'Content-Type': 'multipart/form-data' },
    onUploadProgress: progressEvent => {
    
    
      callback && callback(progressEvent)
    }
  }).then(res => {
    
    
    return res
  }).catch((r) => {
    
    
    console.error(r)
  })
}
export default service

/api/print/server.js

import {
    
     uploadFile } from '@/utils/request'
// 上传打印服务更新包
export function uploadPackage(data,callback) {
    
    
  return uploadFile({
    
    
    url: '/printServer/package/file/upload',
    data: data,
    timeout: 30000,
    callback
  })
}

/views/print/server/index.vue

    // 替换更新包
    replacePackage(item){
    
    
      this.processNum = 0
      console.log('上传的文件:', item)
      const fd = new FormData()
      fd.append('file', item.file)
      // 开启loding
      this.upload_loading = true
      this.pageLoading = true
      uploadPackage(fd, (progressEvent) => {
    
    
          // console.log('上传进度:', progressEvent,parseFloat((progressEvent.loaded / progressEvent.total) * 100).toFixed(1))
          this.processNum = parseFloat((progressEvent.loaded / progressEvent.total) * 100).toFixed(1)
          if(this.processNum>=100){
    
    
            this.pageLoading = false
          }
        }).then(res => {
    
    
          console.log('文件上传结果:', res)
          this.pageLoading = false
          if(res.code===200){
    
    
            this.$modal.msgSuccess('更新包上传成功,稍候更新版本号')
            this.isShowPackageDialog = false
            // this.watchServerPackage()
          } else {
    
    
            this.$modal.msgError(res.msg)
          }
          this.upload_loading = false
          this.$refs.uploader.clearFiles()
        }).catch(err => {
    
    
          console.log('文件上失败:', err)
          this.upload_loading = false
          this.pageLoading = false
          this.$refs.uploader.clearFiles()
        });
    },

猜你喜欢

转载自blog.csdn.net/Amnesiac666/article/details/124974797