axios上传下载文本流数据


上传formdata数据

// 方式 一
var formData = new FormData();
formData.append("username", file); //username 为key名,例:file:xxxx.xlsx
let config = {
    headers: {
        "Content-Type": "multipart/form-data",
    },
};
axios
    .post("url", formData, config)
    .then(res => {
        console.log(res);
        this.$refs.uploadExcel.clearFiles();
        // console.log(res)//返回带headers的全部信息
        if (res.code == 0) {
            this.tongMessage("success", "导入成功");
        }
    })
    .catch(res => {
        console.log(res);
    });

// 方式  二
import qs from "qs";
let config = {
    headers: {
        "Content-Type": "multipart/form-data",
    },
};
const data = qs.stringfy({ username: "test" });
axios
    .post("url", data, config)
    .then(res => {
        console.log(res);
    })
    .catch(res => {
        console.log(res);
    });

下载Excel文件

普通方法下载

axios
    .get("url", {
        parmas: {},
        responseType: "blob", //定义接口响应的格式,很重要
    })
    .then(res => {
        this.$refs.uploadPDF.clearFiles(); //在每一次上传请求结束后清除缓存
        console.log(res); //返回带headers的全部信息,需要修改axios return res.data 为 return res
        const fileName = res.headers["content-disposition"].split("=")[1];
        const link = document.createElement("a"); //创建一个a标签用来跳转
        link.style.display = "none";
        let blob = new Blob([res.data], {
            type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        }); //拿到文件流下载对象 res为接口返回的文件流 设置下载格式.xlsx
        let objectUrl = URL.createObjectURL(blob); //生成文件流下载链接
        link.href = objectUrl; //a标签 href  赋值 链接
        link.download = decodeURI(fileName);
        link.click(); // 下载文件
        URL.revokeObjectURL(objectUrl); // 释放内存
        document.body.removeChild(link); //移除标签节点
    })
    .catch(res => {
        console.log(res);
    });

采用 FileReader 实例对象调用Api ,处理文件流

this.$axios({
    url: "url",
    method: "GET",
    responseType: "blob", //设置响应格式
    headers: {
        "Content-Type": "application/x-www-form-urlencoded",
    },
})
    .then(function (res) {
        const reader = new FileReader(); // 实例化 FileReader
        reader.readAsDataURL(res.data); //将读取到的文件编码成DataURL
        reader.onload = e => {
            //调用API onload  文件读取成功时触发
            //模拟a标签点击
            let a = document.createElement("a"); //创建a标签,
            a.download = Date.parse(new Date()) + ".jpeg"; //设置格式
            a.href = e.target.result; //下载文件流链接
            document.body.appendChild(a); //将标签DOM,放置页面
            a.click();
            document.body.removeChild(a); //移除标签节点
        };
        reader.onerror = e => {
            this.$message({
                message: "解析文件发生错误",
                type: "warning",
            });
        };
        reader.onabort = e => {
            this.$message({
                message: "解析文件发生意外终止",
                type: "warning",
            });
        };
    })
    .catch(function (error) {
        console.log(error);
    });

下载word

downLoad(data) {
    let obj = {
        reportDetailId: data.reportDetailId
    }
    this.$axios.post(this.dataQualityApi.getUrl("reportDownLoad"), obj,{responseType: 'blob'})
        .then((res) => {
        this.downloadFile(res, '报告结果', 'docx');
    });
},
downloadFile(content, fileName, type) {
    let blob = new Blob([content], {
        type: `application/${type}`,
    });
    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        window.navigator.msSaveOrOpenBlob(blob, fileName);
    } else {
        const aLink = document.createElement("a");
        aLink.download = fileName+'.'+type;
        aLink.href = URL.createObjectURL(blob);
        aLink.click();
        URL.revokeObjectURL(blob);
    }
},

使用node中的fs下载

首先,axios 需要配置config["responseType"] = "arraybuffer";

fs.writeFileSync(path, Buffer.from(res)); //res为后端返回的二进制流,通过 responseType:"arraybuffer" 转为buffer

您可能感兴趣的文章:


文章作者: 弈心
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 弈心 !
评论
  目录