欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

JavaScript下載后端返回的文件流的三種方法

 更新時(shí)間:2023年07月20日 12:05:01   作者:碼上暴富  
本文主要介紹了JavaScript下載后端返回的文件流的三種方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧

方法一

后端返回的結(jié)果

/* 創(chuàng)建一個(gè)js寫以下代碼 */
import axios from 'axios';
/*
先安裝: npm install js-file-download
main.js引入  import fileDownload from 'js-file-download';
* */
/*
* url: 請(qǐng)求接口地址
* fileName: 文件名,例如: ccc.png
* */
export function $fileDownload(url, fileName, config = {}) {
    axios.request({
        url: url,
        method: "get",
        data: config.data,
        responseType: 'blob'
    }).then(
        response => {
            console.log("fileName: ", fileName)
            let fileDownload = require('js-file-download');
            fileDownload(response.data, fileName);
            if (typeof config.resolve === 'function') {
                config.resolve();
            }
        },
        error => {
            let hasError = true;
            if (error.response) {
                const status = error.response.status;
                if (status === 401) {
                    hasError = false;
                }
            }
            if (hasError) {
                this.$showError('下載出錯(cuò),請(qǐng)稍后再試');
            }
            if (typeof config.reject === 'function') {
                config.reject();
            }
        }
    );
}
/* 
* 引入import {$fileDownload} from "../../plugin/utils";
* 然后在methods中調(diào)用封裝的$fileDownload即可 
*/
// 打開(kāi)附件
openFile (item) {
	console.log(item);
	/*item {
		id: "D64C87AD4AF51CCFE0537C0AA8C0A129"
		trainingManagementId: "D3E0484993A472DCE0537C0AA8C01C26"
		fileName: "cls_jpg1.jpg"
		filePath: "/data/apcos/6332/app-standard/app-standard/cdtraining/2022_01_24/c1ff8d5b-f254-4297-b4cb-20839a4316f2cls_jpg1.jpg"
		createTime: "2022-01-24 11:26:10"
	}*/
	let url = `${this.url}/cdtraining/api/download?id=${item.id}`
	$fileDownload(url, item.fileName)
},

結(jié)果

方法二

  methods: {
    // 打開(kāi)附件
    openFile(item) {
      this.$axios.get('api', {
        responseType: 'arraybuffer'
      }).then(res => {
        let dt = `data: image/jpeg;base64,${btoa(new Uint8Array(res.data).reduce((data, byte) => data + String.fromCharCode(byte), ''))}`;
        console.log("dt: ", dt);
      });
      // console.log(item);
      // let url = `${this.url}/upload/downloadFile?fileAddress=${item.other}&fileName=${item.fileAddress}`
      // $fileDownload(url, item.fileAddress)
    },
}

結(jié)果

方法三

在downloadFile.js中

export async function downloadFile({ data, headers }) {
    // todo 增加后端報(bào)錯(cuò)時(shí)的錯(cuò)誤捕獲
    // 通過(guò)content-disposition獲取文件名稱
    const fileName = /.*filename=(.*)/i.exec(headers["content-disposition"])?.[1] || "下載";
    // 開(kāi)始下載
    const a = document.createElement("a");
    a.href = (window.URL || window.webkitURL).createObjectURL(
        new Blob([data], {
            type: headers["content-type"]
        })
    );
    a.download = decodeURIComponent((fileName));
    a.dispatchEvent(new MouseEvent("click"));
}

在接口文件api.js

// 導(dǎo)出
export function materialExport(data) {
    return http.post(`/api/import/materialExport`, data, {
        responseType: "arraybuffer" // 須指定返回類型為 arraybuffer
    });
}

在html中引入downloadFile.js, api.js

<template>
    <button @click="handelExport">導(dǎo)出下載</button>
</template>
<script>
import { downloadFile } from @/downloadFile
import { api } from @/api
methods: {
    async handelExoprt() {
        let obj = {}
    }
    if (this.tableData.length === 0) {
        this.$message({
            message: "無(wú)數(shù)據(jù), 不能下載",
            type: "warning"
        })
    }else {
        await downloadFile(await materialExport(obj));
    }
}
</script>

結(jié)果

到此這篇關(guān)于JavaScript下載后端返回的文件流的三種方法的文章就介紹到這了,更多相關(guān)JavaScript下載返回文件流內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論