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;

相关推荐
半个落月3 小时前
用 LangChain 连接远程 MCP:从工具发现到多轮调用闭环
人工智能·后端·node.js
星栈独行6 小时前
Node 框架怎么选?Express、Koa、Egg、NestJS 场景化选型指南
后端·程序人生·node.js
徐小超10 小时前
从一句 Hello World 到完整 RAG 系统:一个 AI 知识库的架构选型实录
langchain·node.js·ai编程
雷工笔记21 小时前
如何查看电脑有没有安装node.js及如何安装node.js
node.js
星栈1 天前
Node 框架怎么选?Express、Koa、Egg、NestJS 场景化选型指南
后端·node.js
万敏1 天前
Vue3 全栈实战第三周:组件化开发完整记录 —— Props / Emit / provide-inject / 插槽 / 自定义指令
vue.js·node.js·全栈
Kel1 天前
Node.js 单线程高并发:从内核中断到 JS 回调的完整技术栈
设计模式·架构·node.js
触底反弹2 天前
🔥 保姆级教程|SSE + BFF + 跨域三件套,从零实现 ChatGPT 流式输出(附完整代码)
人工智能·node.js·vite
柒和远方3 天前
V043:BFF 层流式输出:从前端直连到生产级流式网关的架构演进
javascript·架构·node.js
濮水大叔3 天前
在 DTO 中使用 Form Layout 配置复杂表单,支持 Tabs/Groups/Sections
vue.js·typescript·node.js