JavaScript下載后端返回的文件流的三種方法
更新時間:2023年07月20日 12:05:01 作者:碼上暴富
本文主要介紹了JavaScript下載后端返回的文件流的三種方法,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
方法一
后端返回的結(jié)果
/* 創(chuàng)建一個js寫以下代碼 */ import axios from 'axios'; /* 先安裝: npm install js-file-download main.js引入 import fileDownload from 'js-file-download'; * */ /* * url: 請求接口地址 * 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('下載出錯,請稍后再試'); } if (typeof config.reject === 'function') { config.reject(); } } ); }
/* * 引入import {$fileDownload} from "../../plugin/utils"; * 然后在methods中調(diào)用封裝的$fileDownload即可 */ // 打開附件 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: { // 打開附件 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 增加后端報錯時的錯誤捕獲 // 通過content-disposition獲取文件名稱 const fileName = /.*filename=(.*)/i.exec(headers["content-disposition"])?.[1] || "下載"; // 開始下載 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: "無數(shù)據(jù), 不能下載", type: "warning" }) }else { await downloadFile(await materialExport(obj)); } } </script>
結(jié)果
到此這篇關(guān)于JavaScript下載后端返回的文件流的三種方法的文章就介紹到這了,更多相關(guān)JavaScript下載返回文件流內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
webpack的 rquire.context用法實現(xiàn)工程自動化的方法
這篇文章主要介紹了webpack的 rquire.context用法實現(xiàn)工程自動化的方法,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-02-02解決webpack無法通過IP地址訪問localhost的問題
下面小編就為大家分享一篇解決webpack無法通過IP地址訪問localhost的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-02-02js 去掉空格實例 Trim() LTrim() RTrim()
js 去掉空格實例Trim(),LTrim(),RTrim() 需要的朋友可以過來參考下,希望對大家有所幫助2014-01-01