下载.txt文件 方法有哪些?

1.1. a标签行内 默认 :get请求

html 复制代码
<a href="your-file.pdf" download="desired-filename.pdf">下载文件</a>

1.2. a标签另一种方式

html代码 👇

html 复制代码
<button onclick="downloadCSV()">下载CSV文件</button> 

js代码👇

javascript 复制代码
function downloadCSV() {  
    // 示例CSV数据  
    var csv = "姓名,年龄,职业\n张三,30,软件工程师\n李四,25,数据分析师";  
  
    // 创建一个Blob对象  
    var blob = new Blob([csv], { type: "text/csv;charset=utf-8;" });  
  
    // 创建一个指向Blob的URL  
    var url = URL.createObjectURL(blob);  
  
    // 创建一个a标签并设置属性  
    var a = document.createElement("a");  
    a.href = url;  
    a.download = "example.csv"; // 设置下载文件名  
    document.body.appendChild(a); // 将a标签添加到body中(虽然这一步并非必需,但可以避免某些浏览器的安全限制)  
    a.click(); // 模拟点击以触发下载  
  
    // 清理:从body中移除a标签,并释放URL对象  
    document.body.removeChild(a);  
    window.URL.revokeObjectURL(url);  
} 

2、下载文件 post 请求

html代码👇

html 复制代码
<div @click="downloadData">
    下载表格数据
</div>

js代码👇

javascript 复制代码
    downloadData() {
      downloadData().then(res => {
        // 假设 data 是返回来的二进制数据 const data = res.data
        const url = window.URL.create0bjectURL(
          new Blob([data],{ type: "a application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"})
        )
        const link = document.createElement('a')
        link.style.display = 'none'
        link.href = url
        link.setAttribute('download', 'excel.xlsx')
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
      })
    },

index.js接口文件👇

javascript 复制代码
   export function getDownloadData (data) {	
	 return request({	
	   url: '/soft/downloadApi',	
	   method: 'post',	
	   data: data,	
	   responseType:'blob'	//这个很重要
	})
相关推荐
AI人工智能+电脑小能手1 天前
【大白话说Java面试题】【Java基础篇】第7题:HashMap的get流程是什么
java·后端·面试·哈希算法·散列表·hash-index·hash
我头发多我先学1 天前
C++ 模板全解:从泛型编程初阶到特化、分离编译进阶
java·开发语言·c++
mfxcyh1 天前
使用MobaXterm配置nginx
java·服务器·nginx
木叶子---1 天前
Spring 枚举转换器冲突问题分析与解决
java·python·spring
standovon1 天前
SpringSecurity的配置
java
霸道流氓气质1 天前
SpringBoot+LangChain4j+Ollama+RAG(检索增强生成)实现私有文档向量化检索回答
java·spring boot·后端
就叫飞六吧1 天前
Docker Hub 上主流的nginx发行
java·nginx·docker
MiNG MENS1 天前
基于SpringBoot和Leaflet的行政区划地图掩膜效果实战
java·spring boot·后端
IT_陈寒1 天前
Vite静态资源加载把我坑惨了
前端·人工智能·后端
2601_949814691 天前
Spring Boot中的404错误:原因、影响及处理策略
java·spring boot·后端