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.data[0];

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;

相关推荐
ggaofeng6 小时前
实践NPM打包和使用
前端·npm·node.js
1telescope6 小时前
MacBook 安装 nvm 管理 Node.js 多版本教程
macos·node.js
ggaofeng7 小时前
理解npm的原理
前端·npm·node.js
卜锦元1 天前
EchoChat搭建自己的音视频会议系统01-准备工作
c++·golang·uni-app·node.js·音视频
weixin_427771611 天前
Vite 与 Webpack 模块解析差异
前端·webpack·node.js
鲨莎分不晴1 天前
【实战】老项目焕发新生:从 Webpack 平滑迁移到 Vite 避坑全记录
前端·webpack·node.js
中年程序员一枚1 天前
nuxt安装出现certificate 错误
前端框架·npm·node.js
虹科网络安全1 天前
艾体宝新闻 | Node.js 高危安全漏洞:堆栈溢出可能导致服务器崩溃(CVE-2025-59466)
node.js
JaredYe1 天前
纯 Node.js 的 PDF 转 Markdown 方案:支持图片解析的pdf2md库 `node-pdf-to-markdown`
pdf·node.js·markdown·md·pdf2md
芸简新章1 天前
Node.js学习阶段总结-阶段2
学习·node.js