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;

相关推荐
lhbian3 小时前
node.js下载、安装、设置国内镜像源(永久)(Windows11)
node.js
孪生质数-12 小时前
OpenClaw小龙虾-Skill安装教程及推荐安装列表
ai·node.js·skill·openclaw·clawhub
用户21766998377112 小时前
一个253字节的包,骗了我整个晚上
node.js
大碗不吃辣13 小时前
node脚本练习一之掘金社区自动签到
node.js
請你喝杯Java13 小时前
2026 年 Node.js 版本管理工具对比:nvm、fnm、Volta、asdf、mise
node.js
何中应15 小时前
ubuntu如何安装nvm
linux·运维·ubuntu·node.js
John Song15 小时前
npm查看全局安装了哪些命令
前端·npm·node.js
polaris063015 小时前
Node.js HTTP模块详解:创建服务器、响应请求与客户端请求
服务器·http·node.js
Never_Satisfied1 天前
安装node.js
node.js
前端之虎陈随易1 天前
Vite 8正式发布,内置devtool,Wasm SSR 支持
前端·人工智能·typescript·npm·node.js·wasm