需求是上传一个xlsx后台处理完再返回xlsx流

说起来很坑
我以为在勾子里面

const handleFileSuccess = async (response, file, fileList) => {  
  console.log(response,file)
    let downloadLoadingInstance;  
    upload.open = false;  
    upload.isUploading = false;  
    proxy.$refs["uploadRef"].handleRemove(file);  
    downloadLoadingInstance = ElLoading.service({ text: "正在下载数据,请稍候", background: "rgba(0, 0, 0, 0.7)" });  
    const isBlob = blobValidate(response);
     console.log(isBlob)
     if (isBlob) {
      console.log(response)
      const blob = new Blob([response])
      saveAs(blob, `用户房屋模板_${new Date().getTime()}.xlsx`)
    } 
    downloadLoadingInstance.close();  
    getList();  
};

结果下载文件打不开,不是损坏就是里面是二进制流,到底是什么鬼,我就扛定了
扛了三个小时找到了解决方法

正确的解决方法是

<el-upload
           ref="uploadRef"
           :limit="1"
           accept=".xlsx, .xls"
           :http-request="uploadFile"
           :headers="upload.headers"
           :data="upload.data"
           :disabled="upload.isUploading"
           :on-progress="handleFileUploadProgress"
           :on-success="handleFileSuccess"
           :auto-upload="false"
           drag
        >
           <el-icon class="el-icon--upload"><upload-filled /></el-icon>
           <div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
           <template #tip>
              <div class="el-upload__tip text-center">
                 <span>仅允许导入xls、xlsx格式文件。</span>
                 <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="handleExportTemplate">下载模板</el-link>
              </div>
           </template>
        </el-upload>

若依项目扩展elementUI中upload自定义上传行为 http-request属性

使用 :http-request=“uploadFile”

function uploadFile(param){
    // 获取上传的文件名
    var file = param.file
     //发送请求的参数格式为FormData
     const formData = new FormData();
     formData.append("file",file)
     importData(formData).then(res=>{
      console.log(res)
      const isBlob = blobValidate(res);
      if (isBlob) {
        const blob = new Blob([res])
        saveAs(blob, `用户房屋模板_${new Date().getTime()}.xlsx`)
      } 
     }).catch(err=>{
        console.log(err);
     })
}

如果使用这个 http-request属性
:on-success="handleFileSuccess"这个就失效了,虽然不知道什么原理,作为工具人,我们要学会搬砖

export function importData(data) {
  return request({
    url: '/vae/VaeCustomerHouse/importData',
    responseType: 'blob',
    method: 'post',
    data: data,
  })
}

responseType: ‘blob’, 这个必须加,非常重要,这是文件流。如果不加是无法下载成功

Logo

快速构建 Web 应用程序

更多推荐