axios下载文件

前端

download_file(path,file_name){
      var url = "http://127.0.0.1:6062/api/v1/service/download_attachment"
      axios.get(url,{params:{'path':path}, responseType:'blob'},).then((res)=>{
        let blob = new Blob([res.data], { type: `text/plain;charset=utf-8` });
        // 获取heads中的filename文件名
        let downloadElement = document.createElement("a");
        // 创建下载的链接
        let href = window.URL.createObjectURL(blob);
        downloadElement.href = href;
        // 下载后文件名
        downloadElement.download = file_name;
        document.body.appendChild(downloadElement);
        // 点击下载
        downloadElement.click();         // 下载完成移除元素
        document.body.removeChild(downloadElement);
        // 释放掉blob对象
        })
    }

后端

def download_attachment(request):
    """ 下载文件 """
    from django.http import FileResponse
    file_path = request.GET.get('path', None)
    base_dir = settings.BASE_DIR

    file = open(os.path.join(base_dir, file_path), 'rb')
    response = FileResponse(file)
    response['Content-Type'] = 'application/octet-stream'
    response['Content-Disposition'] = 'attachment'

    return response

你可能感兴趣的:(axios下载文件)