Skip to content

下载文件的方法,可以用于下载图片、文件等。

ts
async function downloadFile(
    res: string | ArrayBuffer | Blob | Promise<ArrayBuffer | Blob>, 
    fileName: string
){
    let e: Blob;
    if(typeof res === 'string') {
        axios.get(res, {responseType: 'blob'}).then((res)=>{
            downloadFile(res, fileName);
        });
        return;
    }else if(res instanceof Promise) {
        res.then((res)=>{
            downloadFile(res, fileName);
        });
        return;
    }else if(res instanceof ArrayBuffer) {
        e = new Blob([res as any]);
    }
    const url = window.URL.createObjectURL(e);
    const a = document.createElement('a');
    a.href = url;
    a.setAttribute('download', fileName);
    a.click();
    window.URL.revokeObjectURL(a.href);
}

需要再请求上加上responseType: 'blob'或者responseType: 'arrayBuffer'

Released under the MIT License.