JavaScript下載后端返回的文件流的三種方法
更新時間:2023年07月20日 12:05:01 作者:碼上暴富
本文主要介紹了JavaScript下載后端返回的文件流的三種方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
方法一
后端返回的結(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
// 導出
export function materialExport(data) {
return http.post(`/api/import/materialExport`, data, {
responseType: "arraybuffer" // 須指定返回類型為 arraybuffer
});
}在html中引入downloadFile.js, api.js
<template>
<button @click="handelExport">導出下載</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é)果

到此這篇關于JavaScript下載后端返回的文件流的三種方法的文章就介紹到這了,更多相關JavaScript下載返回文件流內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
使用JavaScript實現(xiàn)檢測網(wǎng)頁是否為空閑狀態(tài)
最近開發(fā)項目時,常碰到“用戶在一定時間內(nèi)無任何操作時,跳轉(zhuǎn)到某個頁面”的需求,所以本文就來使用JavaScript實現(xiàn)這一要求,需要的可以參考下2024-03-03

