后端代码示例:
const datasrc = await project.dataSource('info_platform_database');
const {
knex
} = datasrc;
const db = 'info_platform';
const name = 'export_data';
const table = `${db}.${name}`;
// 导入文件处理需要的工具
const { Blob, Buffer } = require('node:buffer');
const {
ctx
} = this;
const urlPre = 'https://example.com/';
const params = ctx.request.body;
const sql = `
select
info_platform.content.source_id as source_id
from
info_platform.content
where info_platform.content.source_id >= ${params.minId} and info_platform.content.source_id <= ${params.maxId}
order by
info_platform.content.source_id asc`
let [data] = await knex.raw(sql)
data = data.map(item => urlPre+item.source_id) // 假设文件内容是URL拼接
// 先通过Blob构造文件内的数据,再获取其arrayBuffer数据
const blob = await (new Blob([data.join('\n')], { type: 'text/plain', endings: 'native' })).arrayBuffer();
// 通过Buffer.from将arrayBuffer转换成Buffer,只有Buffer类型才能被顺利传输过去下载
ctx.body = Buffer.from(blob);
前端代码示例:
async (row) => {
const { data } = await axios.post(`https://.../exportUrlFile`, { //调用后端对应接口
minId: row.min_id,
maxId: row.max_id,
}, {
responseType: 'arraybuffer', // 此处需要设置为arraybuffer
});
function download(blob, fileName) {
const url = blobToUrl(blob);
const link = document.createElement('a');
link.style.display = 'none';
link.href = new URL(url);
link.setAttribute('download', fileName);
document.body.appendChild(link);
link.click();
};
function blobToUrl(blob) {
try {
const file = new Blob([blob])
console.log(file);
let url = null;
if (window.createObjectURL !== undefined) {
console.log("createObjectURL");
url = window.createObjectURL(file);
} else if (window.webkitURL !== undefined) {
console.log("webkitURL");
console.log(window.webkitURL)
url = window.webkitURL.createObjectURL(file);
console.log(file);
} else if (window.URL !== undefined) {
console.log("URL");
url = window.URL.createObjectURL(file)
}
return url;
} catch (e) {
console.log(e)
alert('系统出错')
}
};
download(data, 'URL链接.txt')
}