欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 时评 > vue3 下载文件 responseType-blob 或者 a标签

vue3 下载文件 responseType-blob 或者 a标签

2025/2/26 21:53:52 来源:https://blog.csdn.net/qq_44062823/article/details/145830933  浏览:    关键词:vue3 下载文件 responseType-blob 或者 a标签

在 Vue 3 中,你可以使用 axiosfetch 来下载文件,并将 responseType 设置为 blob 以处理二进制数据。以下是一个使用 axios 的示例:

使用 axios 下载文件

  1. 首先,确保你已经安装了 axios

    npm install axios
    
  2. 然后在你的 Vue 组件中使用 axios 下载文件:

    <template><button @click="onDownloadClick">下载文件</button>
    </template><script>
    import { handleFileExport } from '@/utils/exportExcel';
    import { apiGetDownload } from '@/api/encouragementApi';export default {methods: {function onDownloadClick(row: any) {const response = await axios.get('https://example.com/path/to/file', {responseType: 'blob', // 重要:设置响应类型为 blob});.handleFileExport(response )setTimeout(() => {ElMessage.success("下载成功")}, 1000)}},
    };
    </script>
    

在utils/exportExcel.ts

// 后端接口导出 非同源的资源需要下载,可以将其转换为Blob:Url
const handleFileExport = (res:any) => {
if(res.request.responseType==='blob'){let contentDisposition = res.headers['content-disposition']if (!contentDisposition) {contentDisposition = `;filename=${decodeURI(res.headers.filename)}`;}const fileName = window.decodeURI(contentDisposition.split(`filename=`)[1]);const blob = new Blob([res.data], {type: 'text/xlsx',});let downloadUrl = window.URL.createObjectURL(blob);let a = document.createElement('a');a.style.display = 'none';a.href = downloadUrl;a.download = fileName;let event = new MouseEvent('click');a.dispatchEvent(event);
}
};

使用a标签下载

  const url = apiDownloadImportFileStr({encourageTypeId: 1})const link = document.createElement('a')link.href = urllink.click()

关键点

  • responseType: 'blob':这是告诉 axiosfetch 返回一个 Blob 对象,用于处理二进制数据。
  • window.URL.createObjectURL:创建一个临时的 URL,用于下载文件。

注意事项

  • 确保服务器支持跨域请求(CORS),否则可能会遇到跨域问题。
  • 如果文件较大,可能需要考虑分块下载或显示下载进度。

通过这些步骤,你可以在 Vue 3 中实现文件下载功能。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词