iframe标签的使用(二)01——文件下载功能 & 下载方法的抽离 & vue3.0页面结构的应用

iframe标签的使用(二)01——vue3.0页面结构的应用 & 文件下载功能-抽离下载方法-引用方式

效果-下载

在这里插入图片描述

结构
 <el-button type="primary" @click='openFile(attachmentUrl, fileName)'>下载</el-button> 

实例

<label>附件:</label>
<span class='pointer color-1890ff' @click='openFile(attachmentUrl, fileName)'>
    {{ fileName }}
</span>
方法
方式1:封装方法进行引用
//index.ts可省略
import { downloadFile } from '@/axios/index.ts';
//.ts可省略
import useDownFileMethods from '@/views/PersonalCenter/useDownFileMethods.ts'

setup(props) {
    const {openFile} =useDownFileMethods(props)
    return {
        openFile,
    };
}
引用文件

1、src/axios/index.ts

 /**
  * 下载文件通过DFS url
  * @param url
  * @param name
  * @param params
  */
 export const downloadFile = (url: string, name?: string, params?: Object) => {
     axios
         .get(url, {
             params,
             responseType: 'blob'
         })
         .then(res => {
             let fileName = '';
             //判断是否存在 . 如果不存在说明是自己传入
             if (name.indexOf('.') === -1) {
                 fileName = name;
                 fileName += url.length
                     ? '.' + url.substring(url.lastIndexOf('.') + 1, url.length)
                     : '';
             } else {
                 //存在 filename 直接使用
                 fileName = name;
             }
             downloadByBlob(res.data, fileName);
         });
 };

 export const downloadByBlob = (blob: Blob, fileName: string) => {
     //不建议改这个 post 还有get  流下载都通过这种形式
     const b = new Blob([blob],{type:'application/vnd.ms-excel'});
     let link = document.createElement('a');
     const href = URL.createObjectURL(b);
     link.href = href;
     link.download = fileName;
     link.click();
     link = null;
     window.URL.revokeObjectURL(href);
 };

2、src/views/PersonalCenter/useDownFileMethods.ts

/*文件下载 公共方法*/

import {ElMessage} from "element-plus";
import {downloadFile} from "@/axios";
import {reactive} from "vue";

function useDownFileMethods(props) {
    const openFile = (file, fileName) => {
        if (!file) return ElMessage.warning('文件地址不存在!');
        downloadFile(file, fileName);
    }
    return {
        openFile
    }
}

export default useDownFileMethods
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值