koa2文件的上传下载功能

const Router = require("koa-router");

const upload = new Router();

const bodyParser = require("koa-bodyparser");

const multer = require("@koa/multer");

const path = require("path");

const article = require(".../utils/sql");

const { getCurrentTime } = require(".../utils/times");

upload.use(bodyParser());

const storage = multer.diskStorage({

destination: function (req, file, cb) {

const uploadPath = path.join(__dirname, ".../uploads");

cb(null, uploadPath);

},

filename: function (req, file, cb) {

cb(null, file.originalname);

},

});

const uploadFile = multer({ storage: storage });

upload.post("/upload", uploadFile.single("file"), async (ctx) => {

const created_at = getCurrentTime();

const { userId, name, type, size, folderId } = ctx.request.body;

const user_id = userId;

const filename = name;

const folder_id = folderId;

const filePath = path.join(

__dirname,

".../uploads",

ctx.request.file.filename

);

const relativeFilePath = path.relative(

path.join(__dirname, ".../uploads"),

filePath

);

let data = await article.addFile(

user_id,

filename,

size,

folder_id,

type,

created_at,

relativeFilePath

);

ctx.body = {

code: 200,

msg: "创建成功",

data,

};

});

module.exports = upload;

下载功能

const Router = require("koa-router");

const download = new Router();

const bodyParser = require("koa-bodyparser");

download.use(bodyParser());

const article = require(".../utils/sql");

const path = require("path");

const send = require("koa-send"); // 引入 koa-send

const static = require("koa-static"); // 引入 koa-static

download.use(static(path.join(__dirname, ".../uploads")));

download.post("/download", async (ctx) => {

let data = ctx.request.body;

const { id } = data;

let res = await article.downloadFile(id);

if (res.data && res.data.length > 0) {

const file = res.data0;

const filePath = file.relativeFilePath; // 确保这是文件在服务器上的完整路径

console.log(filePath)

await send(ctx, filePath, { root: path.join(__dirname, ".../uploads/") });

} else {

ctx.body = {

code: 404,

msg: "文件未找到",

};

}

});

module.exports = download;

相关推荐
谢小飞8 小时前
大文件上传很难?学会这招,GB文件秒传不是梦
前端·node.js
周小董21 小时前
[1367]npm 安装 canvas 报错 node-gyp ERR
前端·npm·node.js
张龙6872 天前
Node.js 内存泄漏排查实战:从内存曲线到堆快照,一条可复用的定位路径
性能优化·node.js
烂蜻蜓2 天前
Node.js入门教程(七):工作机制
node.js
凌云拓界2 天前
NodeVerdict | .ndv 二进制格式:为 WASM 解码器设计的紧凑布局
安全·架构·开源·node.js·编辑器·软件工程·wasm
凌云拓界3 天前
NodeVerdict | 性能门禁:把追踪数据变成 CI 规则
ci/cd·信息可视化·开源·node.js·bug·数据可视化·安全架构
烂蜻蜓3 天前
Node.js入门教程(五):NVM 管理多版本 Node.js
node.js
接着奏乐接着舞。3 天前
LLM 流式响应:网慢和断线怎么处理?
前端·人工智能·node.js·aigc
MartinYeung53 天前
npm爆发大规模供应链攻击 蠕虫污染 2000+ 个包版本: 深度技术剖析
前端·npm·node.js
鲟迹3 天前
NVM 管理Node.js版本
node.js