前情提要
这两天测试文件下载功能,发现get和post路由有一些区别
环境与实现
后端koa,前端vue
实现
后端文件处理
const fsPromises = require("fs/promises");
const fs = require("fs");
async downloadFile(ctx) {
const name = ctx.params.filename || default.file;
const filename = encodeURIComponent(name);
if (!filename) {
ctx.body = {
code: 500
};
return;
}
const base = path.join(process.cwd(), "dirpath");
const fullpath = path.join(base, filename);
let info;
try {
info = fs.statSync(fullpath);
} catch (err) {
if (err.errno == -2) {
ctx.body = {
code: 500
};
return;
} else {
ctx.body = {
code: 500
};
return;
}
}
const filesize = info?.size;
if (!filesize) {
ctx.body = {
code: 500
};
return;
}
const filestream = fs.createReadStream(fullpath, {
highWaterMark: 1024 * 1024,
encoding: null,
});
ctx.set("Content-Type", "application/octet-stream");
ctx.set("Content-Disposition", `attachment; filename=${filename}`);
ctx.set("Content-Size", `${filesize}`);
ctx.body = filestream;
filestream.on("error", (err) => {
console.log("read error");
ctx.res.destroy();
});
}
前端vue实现
import downloadAxios from 'axios'
async function download(file) {
if (!file?.name) {
return
}
try {
const ret = await downloadAxios.get(`/api/download/${file.name}`, {
responseType: 'blob',
transformResponse: [],
})
if (ret) {
const sb = ret.data
let fileName = decodeURIComponent(file.name)
const blob = new Blob([sb], {
type: 'application/octet-stream',
})
const url = window.URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = fileName
document.body.appendChild(a)
a.click()
window.URL.revokeObjectURL(url)
document.body.removeChild(a)
}
} catch (err) {
console.log(err)
}
}
需要说明的是需要使用原生的axios,由于我的项目对axios进行响应拦截处理过,所以这里我重新引入了axios。而且我偷了懒,没有对后端的文件进行验证,连文件名也是直接前端获取的,em...后续再更新吧
路由
上面是下载具体实现。如果用的是get方法创建路由router.get("/download/:filename", fileController.downloadFile);那么前端下载会成功,如果使用router.post("/download/:filename", fileController.downloadFile);,那么前端获取到的内容会增大,并且文件内容不对。
顺带提一下,fs/promises和fs对比起来,有一些功能是真的很方便,比如const files = await fsPromises.readdir(dir);和const stat = await fsPromises.stat(filePath);,至少这两个功能fs没有,或者我没找到!