diff --git a/docs/zh-CN/components/action.md b/docs/zh-CN/components/action.md index adec49bd2..2f28e052f 100755 --- a/docs/zh-CN/components/action.md +++ b/docs/zh-CN/components/action.md @@ -354,6 +354,35 @@ Content-Disposition: attachment; filename="download.pdf" Access-Control-Expose-Headers: Content-Disposition ``` +## 保存到本地 + +> 1.10.0 及以上版本 + +和前面的下载接口功能类似,但不需要返回 `Content-Disposition` header,只需要解决跨域问题,主要用于一些简单的场景,比如下载文本 + +```schema: scope="body" +{ + "label": "保存", + "type": "action", + "actionType": "saveAs", + "api": "/api/download" +} +``` + +> 这个功能目前还没用到 env 里的 fetcher 方法,不支持 POST + +默认会自动取 url 中的文件名,如果没有的话就需要指定,比如 + +```schema: scope="body" +{ + "label": "保存", + "type": "action", + "actionType": "saveAs", + "fileName": "下载的文件名", + "api": "/api/download" +} +``` + ## 倒计时 主要用于发验证码的场景,通过设置倒计时 `countDown`(单位是秒),让点击按钮后禁用一段时间: diff --git a/src/RootRenderer.tsx b/src/RootRenderer.tsx index 7ecf542fb..a3a722893 100644 --- a/src/RootRenderer.tsx +++ b/src/RootRenderer.tsx @@ -12,6 +12,9 @@ import {filter} from './utils/tpl'; import qs from 'qs'; import pick from 'lodash/pick'; import mapValues from 'lodash/mapValues'; +import {saveAs} from 'file-saver'; +import {normalizeApi} from './utils/api'; +import {AjaxActionSchema} from './renderers/Action'; export interface RootRendererProps extends RootProps { location?: any; @@ -218,6 +221,17 @@ export class RootRenderer extends React.Component { env.copy(filter(action.content || action.copy, ctx, '| raw'), { format: action.copyFormat }); + } else if (action.actionType === 'saveAs') { + // 使用 saveAs 实现下载 + // 不支持 env,除非以后将 saveAs 代码拷过来改 + const api = normalizeApi((action as AjaxActionSchema).api); + if (typeof api.url === 'string') { + let fileName = action.fileName || 'data.txt'; + if (api.url.indexOf('.') !== -1) { + fileName = api.url.split('/').pop(); + } + saveAs(api.url, fileName); + } } } diff --git a/src/renderers/Action.tsx b/src/renderers/Action.tsx index 02bbf189c..3ef1ab027 100644 --- a/src/renderers/Action.tsx +++ b/src/renderers/Action.tsx @@ -184,6 +184,14 @@ export interface DownloadActionSchema actionType: 'download'; } +export interface SaveAsActionSchema + extends Omit { + /** + * 指定为保存到本地 + */ + actionType: 'saveAs'; +} + export interface UrlActionSchema extends ButtonSchema { /** * 指定为打开链接 diff --git a/src/types.ts b/src/types.ts index 388b62611..cd7ad4a27 100644 --- a/src/types.ts +++ b/src/types.ts @@ -85,6 +85,7 @@ export interface Action extends Button { | 'copy' | 'reload' | 'ajax' + | 'saveAs' | 'dialog' | 'drawer' | 'jump'