vue3,下载预览的四种方法之responseType-blob、fileName、a标签下载& axios之post请求写法& 引入js方法文件写法& try和catch、async和await用法

vue3,下载预览的四种方法之responseType-blob、fileName、a标签下载& axios之post请求写法& 引入js方法文件写法& try和catch、async和await用法

页面

在这里插入图片描述

在这里插入图片描述

1.1、按钮下载页面

index.vue

<div>
    <el-button type="primary" @click="handelDowload">下载预览</el-button>
</div>


<script lang="ts" setup>
import axios from "axios";
import { downLoadxls } from "@/utils/utils.js";

// 下载预览
const handelDowload = () => {
    axios({ method: 'POST', url: process.env.VUE_APP_API_HOST + constant.ieopCollaborate + '/collaborate/directory/content/downloadPDF', data: { id: directoryId }, responseType: 'blob' }).then((res) => {
        if (res.data?.code) {
            ElMessage.error(res.data.message)
        } else {
            downLoadxls(res)
            setTimeout(function () {
                ElMessage.success("下载成功")
            }, 1000)
        }
    })
}
</script>

包含4个参数:

  • 请求方式method:POST
  • 请求地址url:url
  • 请求参数data:data
  • 定义类型responseType

浏览器下载效果图

在这里插入图片描述

1.2、表格附件下载页面

index.vue

 <el-table-column align="center" label="相关附件" prop="fileName">
      <template #default="scope">
           <span style="color: #409eff; cursor: pointer"
                                @click="handelDowload(scope.row)">{{scope.row.fileName}}</span>
      </template>
</el-table-column>
1.3、引入的方法文件

srcutilsutils.js

//文件流导出数据处理 方式一
export function downLoadxls(res, fileName) {
  let name;
  if (fileName) {
    name = fileName;
  } else {
    if (res.headers["content-disposition"]) {
      const contentDisposition = res.headers["content-disposition"].split("=");
      name = (contentDisposition && decodeURI(contentDisposition[1])) || "";
    }
  }
  const file = new File([res.data], res.data);
  const href = URL.createObjectURL(file);
  const aTag = document.createElement("a");
  aTag.download = name;
  aTag.target = "_blank";
  aTag.href = href;
  aTag.click();
  URL.revokeObjectURL(href);
}

//文件流导出数据处理 方式二
export function downLoad(res, fileName) {
  let name;
  if (fileName) {
    name = fileName;
  } else {
    if (res.headers["content-disposition"]) {
      const contentDisposition = res.headers["content-disposition"].split("=");
      name = (contentDisposition && decodeURI(contentDisposition[1])) || "";
    }
  }
  const content = res.data
  const blob = new Blob([content])
  const elink = document.createElement('a')
  elink.download = name
  elink.style.display = 'none'
  elink.href= URL.createObjectURL(blob)
  document.body.appendChild(elink)
  elink.click()
  URL.revokeObjectURL(elink.href)
  document.body.removeChild(elink)
}
2、直接使用接口下载的页面

index.vue

<el-table-column align="center" label="相关附件" prop="fileName">
                        <template #default="scope">
                            <span style="color: #409eff; cursor: pointer"
                                @click="handelDowload(scope.row)">{{scope.row.fileName}}</span>
                        </template>
                    </el-table-column>

<script lang="ts" setup>
import axios from '@/utils/request'
// import axios from 'axios'
const handelDowload = (row: any) => {
    console.log(row);
 	axios({ method: 'POST', url: process.env.VUE_APP_API_HOST + constant.fileUpload + '/download?id=' + file.fileId, responseType: 'blob' })
    .then(result => {
        const content = result.data
        const blob = new Blob([content])
        const fileName = file.fileName
        if ('download' in document.createElement('a')) {
            const elink = document.createElement('a')
            elink.download = fileName
            elink.style.display = 'none'
            elink.href = URL.createObjectURL(blob)
            document.body.appendChild(elink)
            elink.click()
            URL.revokeObjectURL(elink.href)
            document.body.removeChild(elink)
        } else {
            navigator.msSaveBlob(blob, fileName)
        }
    })
}    
</script>
3、a标签下载文件

index.vue

<div class="info_file">
  <span class="title_file">附件:</span>
  <span class="text_file">
    <span class="fileName" v-for="item in fileList" :key="item.fileId" @click="downloadFile(item.fileId,item.fileName)">{{ item.fileName }}</span>
  </span>
</div>

<div class="info">
    <div class="title">资质文件:&nbsp;&nbsp;</div>
    <div class="text">
        <div style="cursor: pointer;color:#409eff"
            v-for="item in projOrganizationPatentInfo.qualificationFileVoList" :key="item.id"
            @click="_downloadFileWater(item.id, item.fileName)">
            <Link style="width: 1em; height: 1em; margin-right: 8px;margin-top: 3px" />{{
                item.fileName }}
        </div>
    </div>
    
<span class="span-btn" @click="docDownload(row)" >生成交易函</span>    
</div>


<script>
import { downloadFileApi,downloadFileWaterApi,wordTemplateExportApi } from "@/api/file";
import { uploadFileByA } from "@/utils/tool";
    
// 点击下载附件
async downloadFile(fileId,fileName){
  try {
      let result = await downloadFileApi(fileId)
      if(result.data.size){
        uploadFileByA(result.data,fileName)
      }else{
        this.message.error('下载合同失败,请重试')
      }
  } catch (error) {
      console.log(error)
  }
},
    
// 下载水印附件
const _downloadFileWater=async (id,fileName)=>{
    try {
        let params = {id:id}
        let result = await downloadFileWaterApi(params)
        if (result.status == 200) {
            uploadFileByA(result.data,fileName)
        }
    } catch (error) {
        console.log(error)
    }
}

// 模板文件下载
async docDownload(row){
    try {
        let params = {
            projNo:this.projNo,
            patentProjectId:row.id,
            exportType:1
        }
        console.log(params)
        let result = await wordTemplateExportApi(params)
        if(result.data.size){
            uploadFileByA(result.data,`交易函模板.docx`)
        }else{
            this.message.error('交易函模板下载失败,请重试')
        }
    } catch (error) {
        console.log(error)
    }
},
</script>

<style lang="scss" scoped>
.info_file{
  display: flex;
  .title_file{
    width: 70px;
    flex-shrink: 0;
    display: inline-block;
    text-align: right;
    vertical-align: top;
  }
  .text_file{
    display: inline-block;
    .fileName{
      display: block;
      cursor: pointer;
    }
  }
}
    
.info {
    width: 100%;
    margin-bottom: 20px;
    display: flex;
    color: #666;

    .title {
        width: 15%;
        text-align: right;
        font-weight: bold;
    }

    .text {
        font-size: 14px;
        width: 85%;
        text-align: left;
        white-space: pre-wrap;
        color: #535353;
    }
}
    
.span-btn {
    font-size: 12px;
    display: block;
    color: #409EFF;
    cursor: pointer;
}    
</style>

srcutilstool.js

// a标签下载文件
/**
 * @param {content} 文件流信息 
 * @param {fileName} 附件名称 
 */
export function uploadFileByA(content,fileName){
  const blob = new Blob([content])
  if('download' in document.createElement('a')){
      const elink = document.createElement('a')
      elink.download = fileName
      elink.style.display = 'none'
      elink.href= URL.createObjectURL(blob)
      document.body.appendChild(elink)
      elink.click()
      URL.revokeObjectURL(elink.href)
      document.body.removeChild(elink)
  }else{
      navigator.msSaveBlob(blob,fileName)
  }
}

srcapifile.js

import axios from '@/utils/request'
import { getApiUrl } from "@/utils/tool";
import  constant  from "@/components/constant";
const baseUrl = getApiUrl();

// 下载附件
export const downloadFileApi = (id)=>{
    return axios({
        method:'get',
        url:baseUrl + constant.fileUpload + '/download?id=' + id,
        responseType:'blob'
    })
}
// 下载水印附件
export const downloadFileWaterApi = (params)=>{
    return axios({
        method:'post',
        url:baseUrl + constant.publicCoop + '/mark/file/download',
        data:params,
        responseType:'blob'
    })
}

// 合同模板下载
/**
 * 
 * @param {projNo:项目编号;exportType:0、交易方案  1、交易鉴证函   2、交易通知书} data 
 * @returns 
 */
export const wordTemplateExportApi = (data)=>{
    return axios({
        method:'post',
        // url:'http://27.196.111.34:18080/ieop-pri-property1/word/export',
        url:baseUrl + constant.intellectual + '/word/export',
        responseType:'blob',
        data
    })
}

srcutilstool.js

export function getApiUrl(v) {
  return process.env.VUE_APP_API_HOST
}

srccomponentsconstant.js

/**
 * Created by author on 2023/12/18.
 */
export default {
  intellectual:'/ieop-pri-property', //3知识产权网关标识
  fileUpload:'/yundu-file-wjm', //1知识产权上传文件网关
  publicCoop: "/ieop-mtg-coop", // 2公共网关标识
  ieopCollaborate: "/ieop-mtg-collaborate", // 在线协作网关标识
}

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>