在 Vue.js 中,你可以使用 axios 库来请求接口并处理字节流。假设接口返回的是一个文件的字节流,你可以将其转换为 Blob 对象,然后创建一个链接来下载该文件并保存到本地。以下是一个示例,展示如何实现这一过程:
<template> <div> <button @click="downloadFile">Download File</button> </div> </template> <script> import axios from 'axios'; export default { methods: { async downloadFile() { try { const response = await axios.get('https://your-api-endpoint.com/download', { responseType: 'blob' // 确保响应类型为 blob }); // 创建一个 Blob 对象 const blob = new Blob([response.data], { type: 'application/octet-stream' }); // 创建一个链接元素 const link = document.createElement('a'); link.href = URL.createObjectURL(blob); // 设置下载文件的名称 link.download = 'your-file-name.ext'; // 触发点击事件以下载文件 document.body.appendChild(link); link.click(); // 移除链接元素 document.body.removeChild(link); URL.revokeObjectURL(link.href); } catch (error) { console.error('Error downloading file:', error); } } } } </script>