拆分文件,增加上传接口

This commit is contained in:
539943419 committed 2024-08-11 14:55:37 +08:00
1 parent f22dd54490
commit 737ee87bae
6 files changed
+226 -49

No files matched your search

+48
View File
@@ -0,0 +1,48 @@
import express from "express";
import path from "path";
import fs from "fs";
import { staticPath, api_get } from "../config.js";
export default function useGetApi(app) {
// 不存在文件与文件夹同名的问题
app.use(api_get, (req, res, next) => {
const decodedPath = decodeURIComponent(req.path);
const directoryPath = path.join(staticPath, decodedPath);
fs.stat(directoryPath, (err, stats) => {
if (err) {
console.log(err, directoryPath);
// return res.status(500).json({ error: "Unable to access path" });
return next();
}
if (stats.isDirectory()) {
fs.readdir(directoryPath, (err, files) => {
if (err) {
console.log(err, directoryPath);
return res.status(500).json({ error: "Unable to scan directory" });
}
const fileDetails = files.map(file => {
const filePath = path.join(directoryPath, file);
const stats = fs.statSync(filePath);
return {
name: file,
size: stats.isDirectory() ? undefined : stats.size,
type: stats.isDirectory() ? "directory" : "file",
stats: {
atimeMs: stats.atimeMs,
birthtimeMs: stats.birthtimeMs,
ctimeMs: stats.ctimeMs,
mtimeMs: stats.mtimeMs
}
};
});
res.json(fileDetails);
});
} else {
next();
}
});
});
app.use(api_get, express.static(staticPath));
}
+34
View File
@@ -0,0 +1,34 @@
import path from "path";
import fs from "fs";
import multer from "multer";
import { api_upload, staticPath } from "../config.js";
const storage = multer.memoryStorage();
const upload = multer({ storage: storage }).single('file');
export default function useUploadApi(app) {
app.post(api_upload, upload, (req, res) => {
const decodedPath = decodeURIComponent(req.path).substring(8);
const savePath = path.join(staticPath, decodedPath, req.file.originalname)
// 覆盖写or追加写
const oprateType = req.body.oprateType === 'write' ? 'write' : 'append'
const data = req.file.buffer
if (oprateType === 'write') {
// 覆盖写入
fs.writeFile(savePath, data, (err) => {
if (err) {
return res.status(500).json({ message: 'failed', error: err });
}
res.status(200).json({ message: 'success' });
});
} else {
// 追加写入
fs.appendFile(savePath, data, (err) => {
if (err) {
return res.status(500).json({ message: 'failed', error: err });
}
res.status(200).json({ message: 'success' });
});
}
});
}