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

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

使用 axios 下载文件

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

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

    javascript 复制代码
    <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

javascript 复制代码
// 后端接口导出 非同源的资源需要下载,可以将其转换为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标签下载

javascript 复制代码
  const url = apiDownloadImportFileStr({encourageTypeId: 1})
  const link = document.createElement('a')
  link.href = url
  link.click()

关键点

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

注意事项

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

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

相关推荐
@大迁世界5 分钟前
07.React 中的 createRoot 方法是什么?它具体如何运作?
前端·javascript·react.js·前端框架·ecmascript
January120713 分钟前
VBen Admin Select 选择框选中后仍然显示校验错误提示的解决方案
前端·vben
. . . . .21 分钟前
前端测试框架:Vitest
前端
xiaotao13132 分钟前
什么是 Tailwind CSS
前端·css·css3
战南诚2 小时前
VUE中,keep-alive组件与钩子函数的生命周期
前端·vue.js
发现一只大呆瓜2 小时前
React-彻底搞懂 Redux:从单向数据流到 useReducer 的终极抉择
前端·react.js·面试
霍理迪2 小时前
Vue的响应式和生命周期
前端·javascript·vue.js
李剑一2 小时前
别再瞎写了!Cesium 模型 360° 环绕,4 套源码全公开,项目直接用
前端
小码哥_常2 小时前
Android消息机制:Handler、Looper和Message的深度剖析
前端