【Axios】解决Axios下载二进制文件返回空对象的问题

【Axios】解决Axios下载二进制文件返回空对象的问题

问题背景

在一个基于Vue 3的项目中,我们使用Axios下载Excel文件,但遇到了一个奇怪的问题:文件能成功下载下来,但打开时显示内容为[object Object]无法使用。

当我们执行下载代码:

const response = await downloadTaskResult(task.id)
const blob = new Blob([response], {
    type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })

浏览器控制台打印response发现,它竟然是一个空对象,而不是预期的二进制数据流。

排查过程

1. 检查API函数是否正确设置

首先查看了API函数实现:

export function downloadTaskResult(id) {
   
  return request({
   
    url: `/api/data-clean/tasks/${
     id}/download`,
    method: 'get',
    responseType: 'blob',
    responseHeaders: true
  });
}

确认responseType: 'blob'设置正确,表明我们希望Axios将响应作为二进制数据处理。

2. 尝试用curl直接请求接口

用curl命令直接请求后端接口,确认后端返回的确实是正确的Excel文件:

curl -v -o test_download.xlsx http://127.0.0.1:8000/api/data-clean/tasks/3/download

下载的Excel文件大小正常(约300KB),表明后端返回数据没问题。

3. 检查后端接口代码

查看后端FastAPI的文件下载接口:

@router.get("/tasks/{task_id}/download", summary="下载清洗结果")
async def download_result(
    task_id: int = Path(..., description="任务ID"),
    db: Session = Depends(get_db)
):
    # ...文件查找逻辑省略...
    
    # 获取文件名部分
    file_name = os.path.basename<

你可能感兴趣的:(AI编程,cursor,前端,cursor,json)