添加delete, query的api, 修复上传中文名文件乱码的问题

This commit is contained in:
539943419 committed 2024-08-11 22:39:20 +08:00
1 parent 737ee87bae
commit 64259e37f4
10 files changed
+323 -14

No files matched your search

+46
View File
@@ -0,0 +1,46 @@
import { api, staticPath } from "../config.js";
import path from "path";
import useFsOprateEventCenter from "../hooks/useFsOprateEventCenter.js";
import fs from 'fs'
const fsOprateEventCenter = useFsOprateEventCenter()
function deletePath(targetPath) {
return new Promise((resolve, reject) => {
fs.stat(targetPath, (err, stats) => {
if (err) {
console.log(err)
return reject(err); // 如果获取状态失败,返回错误
}
if (stats.isFile()) {
// 如果是文件,直接删除
fs.unlink(targetPath, (err) => {
if (err) return reject(err);
resolve(); // 删除成功
});
// console.log('delete file')
} else if (stats.isDirectory()) {
// 如果是文件夹,递归删除
fs.rmdir(targetPath, { recursive: true }, (err) => {
if (err) return reject(err);
resolve(); // 删除成功
});
// console.log('delete directory')
} else {
// console.log('unknow file')
// 其他类型(如符号链接等),可以根据需要处理
reject('unknow file'); // 这里选择不处理其他类型
}
});
});
}
export default function useDeleteApi(app) {
app.post(api.delete, (req, res) => {
const decodedPath = decodeURIComponent(req.path).substring(api.delete.length - 1);
const targetPath = path.join(staticPath, decodedPath);
const eventId = fsOprateEventCenter.push(deletePath(targetPath))
res.send({ eventId });
});
}
+3 -1
View File
@@ -1,7 +1,9 @@
import express from "express";
import path from "path";
import fs from "fs";
import { staticPath, api_get } from "../config.js";
import { staticPath, api } from "../config.js";
const api_get = api.get
export default function useGetApi(app) {
// 不存在文件与文件夹同名的问题
+11
View File
@@ -0,0 +1,11 @@
import { api } from "../config.js";
import useFsOprateEventCenter from "../hooks/useFsOprateEventCenter.js";
const fsOprateEventCenter = useFsOprateEventCenter();
export default function useQueryApi(app) {
app.get(api.query, (req, res) => {
const id = req.query.id;
res.json(fsOprateEventCenter.query(id));
});
}
+8 -3
View File
@@ -1,15 +1,20 @@
import path from "path";
import fs from "fs";
import multer from "multer";
import { api_upload, staticPath } from "../config.js";
import { api, staticPath } from "../config.js";
const api_upload = api.upload
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)
// 必须这样传,不然中文乱码
const fileName = req.body.fileName
const decodedPath = decodeURIComponent(req.path).substring(api_upload.length - 1);
const savePath = path.join(staticPath, decodedPath, fileName)
// 覆盖写or追加写
const oprateType = req.body.oprateType === 'write' ? 'write' : 'append'
const data = req.file.buffer