vue txt 文件下载

78 篇文章 2 订阅
52 篇文章 1 订阅
	let json={
		name:'小明',
		age:24,
	},
	let strData = JSON.stringify(json);
	const T_URL = window.URL.createObjectURL(new Blob([strData]));
	const LINK = document.createElement('a');
	LINK.href = T_URL;
	LINK.setAttribute('download', '用户信息');
	LINK.click();
	window.URL.revokeObjectURL(T_URL);
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
当使用Vue下载文本文件时,可能会出现跨域问题。这是因为浏览器的安全策略要求在跨域请求时,服务器必须设置Access-Control-Allow-Origin响应头来允许客户端访问资源。 解决方法: 1. 在服务器端设置Access-Control-Allow-Origin响应头来允许跨域访问。 2. 在Vue中使用axios或fetch等工具发送请求时,需要设置withCredentials为true,以便发送跨域请求时能够携带cookies。 3. 将下载文件的请求改为后端处理,前端通过ajax请求后端,后端返回文件流数据,并设置Content-Disposition响应头来提示浏览器下载文件。 代码示例: 1.设置Access-Control-Allow-Origin响应头 ```js // Node.js Express框架示例 app.use(function(req, res, next) { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS'); res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With'); next(); }); ``` 2.使用axios下载文件 ```js axios.get('/download/file', { responseType: 'blob', withCredentials: true // 携带cookies }).then(res => { const url = window.URL.createObjectURL(new Blob([res.data])) // 创建下载链接 const link = document.createElement('a') link.href = url link.setAttribute('download', 'file.txt') document.body.appendChild(link) link.click() window.URL.revokeObjectURL(url) // 释放资源 }) ``` 3.使用ajax请求后端下载文件 ```js // 后端代码示例(Node.js) router.get('/download/file', function(req, res, next) { const filePath = path.join(__dirname, '../public/file.txt') const fileName = 'file.txt' res.setHeader('Content-Disposition', 'attachment; filename=' + fileName) res.setHeader('Content-Type', 'application/octet-stream') const readStream = fs.createReadStream(filePath) readStream.pipe(res) }) ``` ```js // 前端代码示例 axios({ url: '/download/file', method: 'get', responseType: 'blob', }).then((response) => { const url = window.URL.createObjectURL(new Blob([response.data])) const link = document.createElement('a') link.href = url link.setAttribute('download', 'file.txt') document.body.appendChild(link) link.click() window.URL.revokeObjectURL(url) }) ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值