如题,记录一个简单实现。

前端使用 axios 发送请求:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
downloadFile() {
    var params = {
        "a": this.a,
        "b": this.b,
    } // 可选参数,作为queryString 传给后端
    axios.get('/api/download', {
        params: params,
        responseType:'blob'
    }).then(res => {
        console.log(res);
        let blob = new Blob([res.data], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});
        console.log(blob)
        let url = window.URL.createObjectURL(blob);
        let a = document.createElement("a");
        a.href = url;
        a.download = 'FILENAME.xlsx';
        a.click();
        window.URL.revokeObjectURL(url); 
    });
},

文件类型是Excel, type可设置为:

application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

💡 Tip: 打开调试终端看打印的res对象 也能找到相应的文件类型,复制到 blob 的 type 里即可。

后端以FastAPI为例, 返回一个FileResponse

1
2
3
4
5
6
7
@app.get("/api/download")
async def persons(a: str = None, b: str = None):
    filepath = make_excel(a, b) # 文件所在的路径
    return FileResponse(
        filepath,
        filename="FILENAME.xlsx",
    )

以上只记录一下简单的下载功能。

更多实现有时间再补充,比如:

axios 的 responseType 表示服务器响应的数据类型,可以是 'arraybuffer', 'blob', 'document', 'json','text', 'stream'

FastAPI的返回类型还有 StreamingResponse, 可参考:FastAPI的返回类型