首页 > Web开发 > 详细

js 文件下载,当前页下载,新标签下载____后端返回 GET/POST 文件流,下载文件

时间:2019-07-30 15:57:23      阅读:198      评论:0      收藏:0      [点我收藏+]

import axios from axios;

export default function (url, data = {}, method = GET, params, headers) {
    return new Promise((resolve, reject) => {
        let promise = null;
        if (method === GET) {
            promise = axios.get(url, {params: data, headers});
        } else if (method === POST) {
            promise = axios.post(url, data, {params: params, headers});
        }
        promise
            .then(response => resolve(response))
            .catch(err => {
                // console.log("/src/axios/ajax.js----error: "+err)
                reject(err);
            });
    });
}

1. 直接用 Ajax 发 POST/GET 请求

export const requestDownloadLabFile = (id) => { // 下载附件
    const url = preFixed + /lab/myExperimentOperator/download/ + id;

    ajax(url, {}, GET, {}, {labAuth: http://localhost:7000}).then(res=> {
            const content = res.data;
            const blob = new Blob([content]);
            const fileName = fileName.type;
            if (download in document.createElement(a)) { // 非IE下载
                const elink = document.createElement(a);
                elink.download = fileName;
                elink.style.display = none;
                elink.href = URL.createObjectURL(blob);
                document.body.appendChild(elink);
                elink.click();
                URL.revokeObjectURL(elink.href); // 释放URL 对象
                document.body.removeChild(elink);
            } else { // IE10+下载
                navigator.msSaveBlob(blob, fileName);
            }
    });
    return 0;
}

form 当前页下载: (当 链接失效 时,影响当前页,)

export const diyDownload = (url, data, method = GET) => {
    const body = document.getElementsByTagName(body)[0];
    const form = document.createElement(form);
    form.method = method;
    form.action = url;
    for (let key in data) {
        let param = document.createElement(input);
        param.type = hidden;
        param.name = key;
        param.value = data[key];
        form.appendChild(param);
    }
    body.appendChild(form);
    form.submit();
    body.removeChild(form);
};


export const requestDownloadLabFile = (id) => { // 下载附件
    const url = preFixed + /lab/myExperimentOperator/download/ + id;
    diyDownload(url, {}, GET);
};

 iframe 标签下载: (当 链接失效 时,不会影响当前页)

export const requestDownloadLabFile = (id) => { // 下载附件
    const url = preFixed + ‘/lab/myExperimentOperator/download/‘ + id;

    try {
        let elemIF = document.createElement(‘iframe‘);
        elemIF.src = url;
        elemIF.style.display = ‘none‘;
        document.body.appendChild(elemIF);
    } catch (e) {
        myConsole(‘下载异常!‘);
    }
};

js 文件下载,当前页下载,新标签下载____后端返回 GET/POST 文件流,下载文件

原文:https://www.cnblogs.com/baixiaoxiao/p/11270341.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!