# DRF接口 + Vue实现下载文件

### 后端：django-drf

```python
# 下载代码

    @action(methods=['get'], detail=False)
    def download(self, request, *args, **kwargs):
        # 1 读取数据库数据
        obj_data = DmModel.objects.all()
        ws = xlwt.Workbook(encoding='utf-8')
        st = ws.add_sheet('sheet1')
        # 写标题行
        st.write(0, 0, 'ID')
        st.write(0, 1, '域名')
        st.write(0, 2, '访问量')
        st.write(0, 3, '跳转地址')
        st.write(0, 4, '域名组')
        st.write(0, 5, '添加时间')
        # 写入数据，从第一行开始
        excel_row = 1
        for obj in obj_data:
            st.write(excel_row, 0, obj.id)
            st.write(excel_row, 1, obj.domain)
            st.write(excel_row, 2, obj.looks)
            st.write(excel_row, 3, obj.rewrite_url)
            st.write(excel_row, 4, obj.group.group_name)
            st.write(excel_row, 5, str(obj.ct_time))
            excel_row += 1

        # 将数据写入io数据流，不用在本地生成excel文件，不然效率就低了
        output = BytesIO()
        ws.save(output)
        output.seek(0)
        # print(sio.getvalue())
        
        # 将excel数据响应回客户端
        response = HttpResponse(output.getvalue(), content_type='application/vnd.ms-excel')
        response['Content-Disposition'] = 'attachment; filename=xx.xls'
        response.write(output.getvalue())

        return response
```

### vue-admin-template

* 页面

```html
    <el-button type="primary" icon="el-icon-plus" @click="onDownload()"></el-button>


    // 导出执行函数
      onDownload() {
        getDmDownload().then(response => {
         var fileURL = window.URL.createObjectURL(new Blob([response]));
         var fileLink = document.createElement('a');
      
         fileLink.href = fileURL;
         fileLink.setAttribute('download', 'xx.xls');
         document.body.appendChild(fileLink);
       
         fileLink.click();
        })
      },
```

* 接口

```js
import request from '@/utils/request'

export function getDmDownload() {
  return request({
    url: '/v1/dm/download/',
    method: 'get',
    responseType: 'blob'
  })
}
```

### 参考： <https://www.cnblogs.com/clschao/articles/14302188.html>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://close.gitbook.io/yun-wei-bi-ji/python/drf/drf-jie-kou-+-vue-shi-xian-xia-zai-wen-jian.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
