JavaScript下载后端返回的文件流
Posted 码上暴富
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JavaScript下载后端返回的文件流相关的知识,希望对你有一定的参考价值。
javascript下载后端返回的文件流
JavaScript下载后端返回的文件流(方法一)
后端返回的结果
/* 创建一个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中调用封装的$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)
,
结果
JavaScript下载后端返回的文件流(方法二)
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)
,
结果
以上是关于JavaScript下载后端返回的文件流的主要内容,如果未能解决你的问题,请参考以下文章