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;

  • 6
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
好的,以下是基于 TypeScript、Koakoa-body 实现的文件上传代码示例: ```typescript import Koa from 'koa'; import koaBody from 'koa-body'; const app = new Koa(); // 设置上传文件的保存路径 const uploadDir = './uploads'; // koa-body 中间件配置 const koaBodyConfig = { multipart: true, // 启用文件上传 formidable: { uploadDir, // 文件保存路径 keepExtensions: true, // 保留文件扩展名 }, }; // 注册 koa-body 中间件 app.use(koaBody(koaBodyConfig)); app.use(async (ctx) => { // 判断是否为文件上传请求 if (ctx.request.files && ctx.request.files.file) { const { file } = ctx.request.files; // 输出上传文件信息 console.log(`Received file: ${file.name}`); console.log(`File size: ${file.size}`); console.log(`File path: ${file.path}`); ctx.body = 'File uploaded successfully.'; } else { ctx.body = 'Hello World!'; } }); app.listen(3000, () => { console.log('Server is running on http://localhost:3000'); }); ``` 以上代码中,我们通过 `koa-body` 中间件启用了文件上传功能,并且设置了上传文件的保存路径。当接收到文件上传请求时,我们可以通过 `ctx.request.files.file` 获取上传的文件信息,然后对文件进行处理。如果不是文件上传请求,我们只是简单地返回了一个 "Hello World!" 字符串。 注意,我们在代码中没有对文件进行任何处理,只是输出了一些文件信息。在实际项目中,我们需要对上传的文件进行校验、存储和处理。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lionliu0519

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值