feat: 添加上传文件接口

This commit is contained in:
539943419 committed 2024-08-16 17:04:19 +08:00
1 parent 59dbbb288c
commit 28ee6daab4
4 files changed
+36 -12

No files matched your search

+23
View File
@@ -0,0 +1,23 @@
import fs from 'fs'
import path from 'path'
import express from 'express'
import { api, staticPath } from '../config.js'
export default function useMkdirApi(app) {
app.post(api.mkdir, express.json(), (req, res) => {
const folderName = req.body.folderName
const decodedPath = decodeURIComponent(req.path).substring(
api.mkdir.length - 1
)
const mkdirPath = path.join(staticPath, decodedPath, folderName)
// res.status(200).json({ mkdirPath, folderName })
// 创建文件夹
fs.mkdir(mkdirPath, { recursive: true }, (err) => {
if (err) {
return res.status(500).json({ message: 'failed', error: err })
}
res.status(200).json({ message: 'success' })
})
})
}
+4 -6
View File
@@ -3,22 +3,20 @@ import fs from "fs";
import multer from "multer";
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) => {
app.post(api.upload, upload, (req, res) => {
// 必须这样传,不然中文乱码
const fileName = req.body.fileName
const decodedPath = decodeURIComponent(req.path).substring(api_upload.length - 1);
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 operateType = req.body.operateType === 'write' ? 'write' : 'append'
const data = req.file.buffer
if (oprateType === 'write') {
if (operateType === 'write') {
// 覆盖写入
fs.writeFile(savePath, data, (err) => {
if (err) {
+7 -6
View File
@@ -5,12 +5,13 @@ export const staticPath = path.join("./static");
export const port = 17705;
export const api = {
get: `/${"get"}`,
query: `/${"query"}`,
upload: `/${"upload"}/*`,
delete: `/${"delete"}/*`,
rename: `/${"rename"}/*`,
cut: `/${"cut"}/*`,
get: `/${'get'}`,
query: `/${'query'}`,
upload: `/${'upload'}/*`,
delete: `/${'delete'}/*`,
rename: `/${'rename'}/*`,
mkdir: `/${'mkdir'}/*`,
cut: `/${'cut'}/*`
}
export default { staticPath, port, api }
+2
View File
@@ -9,6 +9,7 @@ import useDeleteApi from "./api/useDeleteApi.js";
import useQueryApi from "./api/useQueryApi.js";
import useRenameApi from "./api/useRenameApi.js";
import useCutApi from "./api/useCutApi.js";
import useMkdirApi from "./api/useMkdirApi.js";
const { staticPath, port, api } = Config;
@@ -25,6 +26,7 @@ useDeleteApi(app);
useQueryApi(app);
useRenameApi(app);
useCutApi(app);
useMkdirApi(app);
app.listen(port, "::", () => {
const interfaces = os.networkInterfaces();