This commit is contained in:
nanguaboss
2026-08-03 00:07:01 +08:00
commit 71c6e8d9c1
112 changed files with 7815 additions and 0 deletions
+75
View File
@@ -0,0 +1,75 @@
<?php
/**
* 文件上传接口 POST /api/document/upload.php (multipart/form-data, 字段名 file)
* 可选:doc_name(默认取原文件名)/ tags(JSON)
* 存储:static/uploads/documents/年/月/随机文件名
* 返回:相对路径 storage_path
*/
require_once __DIR__ . '/../common/db.php';
require_once __DIR__ . '/../common/response.php';
require_once __DIR__ . '/../common/auth.php';
require_once __DIR__ . '/../common/logger.php';
checkAjax();
checkPermission('document');
if (empty($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
Response::error('请选择要上传的文件', 400);
}
$file = $_FILES['file'];
$maxSize = 50 * 1024 * 1024; // 50MB
if ($file['size'] > $maxSize) {
Response::error('文件不能超过50MB', 400);
}
// 安全扩展名白名单
$extMap = [
'pdf' => 'application/pdf', 'doc' => 'application/msword',
'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'xls' => 'application/vnd.ms-excel',
'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'ppt' => 'application/vnd.ms-powerpoint',
'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
'txt' => 'text/plain', 'csv' => 'text/csv', 'png' => 'image/png',
'jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'gif' => 'image/gif',
'zip' => 'application/zip', 'rar' => 'application/x-rar-compressed',
];
$ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
if (!isset($extMap[$ext])) {
Response::error('不允许的文件类型:' . ($ext !== '' ? $ext : '无扩展名'), 400);
}
// 目录:static/uploads/documents/年/月
$baseDir = __DIR__ . '/../../static/uploads/documents';
$subDir = date('Y') . '/' . date('m');
$dir = $baseDir . '/' . $subDir;
if (!is_dir($dir) && !mkdir($dir, 0777, true)) {
Response::error('创建上传目录失败', 500);
}
$newName = date('YmdHis') . '_' . substr(uniqid(), -6) . '.' . $ext;
$dest = $dir . '/' . $newName;
if (!move_uploaded_file($file['tmp_name'], $dest)) {
Response::error('文件保存失败', 500);
}
$storagePath = 'static/uploads/documents/' . $subDir . '/' . $newName;
$docName = trim($_POST['doc_name'] ?? '') !== '' ? trim($_POST['doc_name']) : $file['name'];
$tags = $_POST['tags'] ?? null;
$tagsJson = null;
if ($tags !== null && $tags !== '') {
$decoded = json_decode($tags, true);
$tagsJson = is_array($decoded) ? json_encode($decoded, JSON_UNESCAPED_UNICODE) : null;
}
$pdo = DB::getInstance()->getPdo();
$stmt = $pdo->prepare(
"INSERT INTO company_documents (doc_name, storage_path, file_type, is_current, document_source, tags)
VALUES (?, ?, ?, 1, ?, ?)"
);
$stmt->execute([$docName, $storagePath, $extMap[$ext], '本地上传', $tagsJson]);
$newId = (int)$pdo->lastInsertId();
logCurrent('upload', 'document', 'company_documents', $newId, ['doc_name' => $docName, 'storage_path' => $storagePath]);
Response::success(['id' => $newId, 'storage_path' => $storagePath, 'doc_name' => $docName], '上传成功');