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: “文件未找到”,
};
}
});文章来源:https://www.toymoban.com/news/detail-788052.html
module.exports = download;文章来源地址https://www.toymoban.com/news/detail-788052.html
到了这里,关于koa2文件的上传下载功能的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!