Skip to content

Commit c1d8c27

Browse files
committed
feat: add util methods
1 parent b6e15aa commit c1d8c27

3 files changed

Lines changed: 72 additions & 0 deletions

File tree

README.md

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,19 @@
11
# upload-file-service
22
nodejs 实现文件上传功能
3+
4+
5+
### 创建表的字段说明
6+
7+
| 字段名称 | 类型 | 描述 |
8+
|---------------|----------------|------------------------|
9+
| id | INT | 自动增量的主键 |
10+
| 文件名 | VARCHAR(255) | 文件的名称 |
11+
| 文件大小 | BIGINT | 文件的大小(以字节为单位) |
12+
| 文件地址 | VARCHAR(255) | 文件的存储地址 |
13+
| 创建人 | VARCHAR(255) | 创建文件的用户 |
14+
| 创建时间 | TIMESTAMP | 文件的创建时间 |
15+
| 更新人 | VARCHAR(255) | 更新文件的用户 |
16+
| 更新时间 | TIMESTAMP | 文件的更新时间 |
17+
| 是否公开 | BOOLEAN | 文件是否公开 |
18+
| 公开失效时间 | TIMESTAMP | 文件公开的失效时间 |
19+
| 公开人 | VARCHAR(255) | 设置文件公开的用户 |

utils/appendSuffixToFilename.js

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
function appendSuffixToFilename(filename, suffix) {
2+
// 找到最后一个点的位置
3+
const lastDotIndex = filename.lastIndexOf('.');
4+
// 如果找到了点,则在点之前插入后缀
5+
if (lastDotIndex !== -1) {
6+
return `${filename.substring(
7+
0,
8+
lastDotIndex
9+
)}_${suffix}${filename.substring(lastDotIndex)}`;
10+
} else {
11+
// 如果没有点,直接在末尾添加后缀
12+
return `${filename}_${suffix}`;
13+
}
14+
}
15+
16+
module.exports = { appendSuffixToFilename };
17+

utils/createPath.js

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
const fs = require('fs');
2+
const path = require('path');
3+
4+
// 检查路径是否为文件
5+
function isFile(filePath) {
6+
return path.extname(filePath) !== '';
7+
}
8+
9+
// 递归创建目录
10+
function mkdirsSync(dirPath) {
11+
if (fs.existsSync(dirPath)) {
12+
return;
13+
}
14+
const parentDir = path.dirname(dirPath);
15+
mkdirsSync(parentDir);
16+
fs.mkdirSync(dirPath);
17+
}
18+
19+
// 创建文件,如果父目录不存在则递归创建
20+
function createFile(filePath) {
21+
const dirPath = path.dirname(filePath);
22+
mkdirsSync(dirPath);
23+
fs.writeFileSync(filePath, '');
24+
}
25+
26+
// 创建目录或文件
27+
function createPath(filePath) {
28+
if (isFile(filePath)) {
29+
createFile(filePath);
30+
} else {
31+
mkdirsSync(filePath);
32+
}
33+
}
34+
35+
module.exports = {
36+
createPath,
37+
createPath
38+
};

0 commit comments

Comments
 (0)