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;

相关推荐
天天进步20151 小时前
Node.js中Express框架入门教程
node.js·express
爱心发电丶6 小时前
NodeSSh 实现前端自动部署:服务端编译和本地编译
node.js
Face6 小时前
Node.js全栈基石(壹)
前端·node.js
mosen8688 小时前
易混淆的CommonJS和ESM(ES Module)及它们区别
javascript·node.js·express
袁袁袁袁满1 天前
基于nvm安装管理多个node.js版本切换使用(附上详细安装使用图文教程+nvm命令大全)
运维·node.js·nvm·nvm安装·多个node.js版本切换使用·nvm命令大全·node.js安装
Q_Q5110082851 天前
python的校园研招网系统
开发语言·spring boot·python·django·flask·node.js·php
棒棒的唐1 天前
nodejs安装后 使用npm 只能在cmd 里使用 ,但是不能在poowershell使用,只能用npm.cmd
前端·npm·node.js
G等你下课1 天前
基于MCP构建一个智能助手
前端·node.js·mcp
JSPanda1 天前
Webpack插件开发避坑指南:三招制服Dev Server兼容性
webpack·node.js
濮水大叔2 天前
这个Database Transaction功能多多,你用过吗?
typescript·node.js·nestjs