axios下载Django返回的二进制文件

后端

from django.http import FileResponse
import pandas as pd
from io import BytesIO

def download(request):
    buffer = BytesIO()
    queryset = xxx.objects.values_list('a','b')  # 用values_list省内存
    df = pd.DataFrame(list(queryset),columns=['a','b'])  # 创建pandas数据集
    with pd.ExcelWriter(buffer) as writer:
        df.to_excel(writer,index=False)  # 将数据集写入内存
    buffer.seek(0)  # 必须有这步
    return FileResponse(buffer, as_attachment=True)

前端

axios({
   url:'xxx',
   method:'post',
   data:data
   responseType:'blob'    // 重要
}).then(res => {
   const a = document.createElement('a')
   a.style.display = 'none'
   a.href = window.URL.createObjectURL(new Blob([res.data]))
   a.setAttribute('download','文件名') // 设置文件名    
   document.body.appendChild(a)
   a.click()
   document.body.removeChild(a)  
})

 

posted @ 2021-11-23 15:33  Maltone  阅读(218)  评论(0)    收藏  举报