当前位置:网站首页 > Vue.js开发 > 正文

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、引入的方法文件

src\utils\utils.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: #; } } .span-btn { font-size: 12px; display: block; color: #409EFF; cursor: pointer; } </style> 

src\utils\tool.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) } } 

src\api\file.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 }) } 

src\utils\tool.js

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

src\components\constant.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", // 在线协作网关标识 } 
到此这篇vue3,下载预览的四种方法之responseType-blob、fileName、a标签下载& axios之post请求写法& 引入js方法文件写法& try和catch、async和await用法的文章就介绍到这了,更多相关内容请继续浏览下面的相关推荐文章,希望大家都能在编程的领域有一番成就!

版权声明


相关文章:

  • vue3中,wangEditor富文本组件的使用——.disable()富文本禁用、toolbarKeys配置菜单、shallowRef()创建实例、.destroy()销毁富文本、内容为html格式2024-12-01 12:18:08
  • vue3中,el-table表格中基础的查询、重置、新增、编辑回显、删除2024-12-01 12:18:08
  • vue3中,el-table表格的禁用、回显和多选操作——标识row-key、是否勾选selectable & toggleRowSelection(row, true)-true选中2024-12-01 12:18:08
  • vue3中,tabs标签页的使用、调用方法实现动态style2024-12-01 12:18:08
  • vue3中,项目甘特图实现项目进度条——封装组件之tabs标签页的使用、定义方法实现动态样式style、reduce方法、数组每个下标对应的当前下标前几位之和、new Date()转换日期格式2024-12-01 12:18:08
  • vue3中,渲染动态表单(三)——梳理动态表单的几种类型、树结构表格row-key、父子传值之props、emit和defineEmits & ElLoading组件用法和post请求动态地址2024-12-01 12:18:08
  • vue3中,渲染动态表单(二)——使用wangEditor组件 & vue3基础页面的写法之defineComponent、toRefs、reactive和return & main文件注册全局组件2024-12-01 12:18:08
  • vue3中,渲染动态表单(一)——定义公共样式、使用动态样式class & 抽离el-dialog对话框组件 & 父子传参 & 自定义slot插槽 & vue3中watch写法和computed写法2024-12-01 12:18:08
  • vue中provide和inject的用法2024-12-01 12:18:08
  • vue3中,axios的几种用法之抽离接口、post请求、get请求、.env.dev、网关标识、基准地址2024-12-01 12:18:08
  • 全屏图片