amis下载文件的几种写法示例
·
一、静态cdn资源文件下载
1.url
| 属性名 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| url | string |
- | 按钮点击后,会打开指定页面。可用 ${xxx} 取值 |
| blank | boolean |
false |
如果为 true 将在新 tab 页面打开 |
| params | object |
- | 页面参数{key:value},支持数据映射,> 1.10.0 及以上版本 |
{
"url": "https://xxx.com/static/xxx/xxx导入模板.xlsx",
"type": "button",
"blank": false,
"label": "xxx导入模板下载",
"level": "primary",
"actionType": "url"
}
缺点:点击下载会先出现白屏,过一会儿才恢复正常
2.tpl利用a标签下载
{
"id": "u:xxxxx",
"type": "tpl",
"tpl": "<a href='https://xxx.com/static/xxx/xxx导入模板.xlsx' download=\"xxx导入模板.xlsx\">附件下载</a>"
}
二、接口返回的文件流
1.ajax
通用方法,注意要加"responseType": "blob",否则下载文件后会提示不支持的格式打不开:
{
"api": {
... // 其他配置
"responseType": "blob"
}
}
代码示例:
{
"id": "u:xxxxx",
"api": {
"url": "/api/xxx/downloadMyFile",
"data": {
"fileId": "${fileId}"
},
"method": "get",
"responseType": "blob"
},
"type": "button",
"label": "附件下载",
"level": "link",
"style": {
"padding": 0
},
"actionType": "ajax"
}
2.a标签
注意: 适合简单的get请求,如果接口要求headers参数之类的,a标签方式就不适合了,一旦发现a标签不行就换成ajax方式
{
"id": "u:xxxxx",
"type": "tpl",
"tpl": "<a href='/api/api/xxx/downloadMyFile?fileId=${fileId}' class='block cxd-Button--link'>附件下载</a>"
}
三、接口返回的是base64格式
- 先使用ajax获取base64字符串,再加上前缀:'data:application/octet-stream;base64,'
- 拼接成'data:application/octet-stream;base64,xxx'格式,js创建使用a标签下载,下载完销毁a标签
{
"type": "page",
"id": "u:xxx",
"pullRefresh": {
"disabled": true
},
"css": {
".my-page .cxd-Form-item--horizontal .cxd-Form-itemColumn--normal": {
"width": "120px !important"
}
},
"regions": [
"body",
"header"
],
"data": {
"attachId": "${attachId}",
"result": {}
},
"onEvent": {
"init": {
"actions": [
{
"script": "window.downloadMyBase64File=(url,fileName)=>{const mimeType='application/octet-stream';const elink = document.createElement('a');elink.href = 'data:'+mimeType+';base64,'+url;elink.target = '_self';elink.setAttribute('download', fileName);elink.style.display = 'none';document.body.appendChild(elink);elink.click();document.body.removeChild(elink);};",
"actionType": "custom"
}
]
}
},
"asideResizor": false,
"className": "my-page",
"body": [
{
"type": "button",
"id": "u:xxx",
"api": {
"url": "/api/xxx/downloadBase64File",
"data": {
"attachId": "${attachId}"
},
"method": "post",
"adaptor": "const fileName='xxx.jpg';window.downloadMyBase64File(payload.data.result,fileName);return payload;"
},
"label": "下载附件",
"level": "link",
"actionType": "ajax"
}
]
}
参考资料:
button
https://aisuda.bce.baidu.com/amis/zh-CN/components/button#%E5%B1%9E%E6%80%A7%E8%A1%A8actions
https://aisuda.bce.baidu.com/amis/zh-CN/components/action#%E7%9B%B4%E6%8E%A5%E8%B7%B3%E8%BD%ACapi-配置文件下载
https://aisuda.bce.baidu.com/amis/zh-CN/docs/types/api#%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6%E4%B8%8B%E8%BD%BD
更多推荐


所有评论(0)