1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683
| const express = require('express'); const cors = require('cors'); const multer = require('multer'); const path = require('path'); const fs = require('fs'); const fsPromises = fs.promises;
const app = express(); const port = 3000;
const UPLOAD_DIR = path.resolve(__dirname, 'uploads'); const TEMP_DIR = path.resolve(UPLOAD_DIR, 'temp');
const ensureUploadDirs = () => { console.log('检查上传目录...'); try { if (!fs.existsSync(UPLOAD_DIR)) { console.log(`创建上传目录: ${UPLOAD_DIR}`); fs.mkdirSync(UPLOAD_DIR, { recursive: true }); } if (!fs.existsSync(TEMP_DIR)) { console.log(`创建临时目录: ${TEMP_DIR}`); fs.mkdirSync(TEMP_DIR, { recursive: true }); } try { const testFile = path.join(TEMP_DIR, '.test'); fs.writeFileSync(testFile, 'test'); fs.unlinkSync(testFile); console.log('目录权限检查通过'); } catch (error) { console.error('目录写入权限检查失败:', error); console.error('请确保应用程序有上传目录的写入权限'); throw new Error('目录权限错误,无法进行文件上传'); } console.log('上传目录检查完成'); } catch (error) { console.error('创建上传目录失败:', error); throw error; } };
ensureUploadDirs();
const corsOptions = { origin: '*', methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], allowedHeaders: ['Content-Type', 'Authorization'], credentials: true, maxAge: 86400 };
app.use(express.urlencoded({ extended: true, limit: '50mb' })); app.use(express.json());
const upload = multer({ storage: multer.diskStorage({ destination: function (req, file, cb) { cb(null, TEMP_DIR); }, filename: function (req, file, cb) { cb(null, Date.now() + '-' + file.originalname); } }), limits: { fileSize: 50 * 1024 * 1024, } });
app.use(cors(corsOptions));
app.get('/', (req, res) => { res.json({ message: 'Express 服务器正在运行!' }); });
app.post('/api/check', async (req, res) => { try { const { fileHash, filename } = req.body; if (!fileHash) { return res.status(400).json({ exists: false, message: '缺少必要参数: fileHash' }); } console.log(`检查文件是否存在: fileHash=${fileHash}, filename=${filename}`); const ext = filename ? path.extname(filename) : ''; const files = await fsPromises.readdir(UPLOAD_DIR); const exists = files.some(file => { if (file.endsWith('.json')) { return false; } const fileBaseName = path.basename(file, path.extname(file)); return fileBaseName === fileHash; }); console.log(`文件${exists ? '已存在' : '不存在'}: ${fileHash}`); let fileUrl = null; if (exists) { const actualFile = files.find(file => { if (file.endsWith('.json')) return false; return path.basename(file, path.extname(file)) === fileHash; }); if (actualFile) { fileUrl = `/uploads/${actualFile}`; } } res.json({ exists, message: exists ? '文件已存在,可以秒传' : '文件不存在,需要上传', url: fileUrl }); } catch (error) { console.error('检查文件是否存在出错:', error); res.status(500).json({ exists: false, message: '服务器错误', error: error.toString() }); } });
app.get('/api/uploaded/chunks', async (req, res) => { try { const { fileHash } = req.query; const chunkDir = path.resolve(TEMP_DIR, fileHash); let uploadedChunks = []; if (fs.existsSync(chunkDir)) { const files = await fsPromises.readdir(chunkDir); uploadedChunks = files.map(Number).sort((a, b) => a - b); } res.json({ uploadedChunks, message: `已上传${uploadedChunks.length}个分片` }); } catch (error) { console.error('获取已上传分片出错:', error); res.status(500).json({ uploadedChunks: [], message: '服务器错误' }); } });
app.post('/api/upload/chunk', upload.single('chunk'), async (req, res) => { try { console.log('收到上传请求,准备处理文件分片'); if (!req.file) { console.error('请求中没有找到文件'); return res.status(400).json({ success: false, message: '请求中未找到文件' }); } const { fileHash, chunkIndex, filename } = req.body; console.log('分片上传请求参数:', { fileHash, chunkIndex, filename, tempFile: req.file.path }); if (!fileHash || chunkIndex === undefined) { console.error('请求参数不完整'); return res.status(400).json({ success: false, message: '请求参数不完整,需要 fileHash 和 chunkIndex' }); } const chunkDir = path.resolve(TEMP_DIR, fileHash); if (!fs.existsSync(chunkDir)) { console.log(`创建分片目录: ${chunkDir}`); fs.mkdirSync(chunkDir, { recursive: true }); } const finalPath = path.resolve(chunkDir, `${chunkIndex}`); try { if (fs.existsSync(finalPath)) { await fsPromises.unlink(finalPath); } const data = await fsPromises.readFile(req.file.path); await fsPromises.writeFile(finalPath, data); await fsPromises.unlink(req.file.path); console.log(`分片移动成功: ${req.file.path} -> ${finalPath}`); } catch (err) { console.error('移动分片文件失败:', err); return res.status(500).json({ success: false, message: '保存分片失败: ' + err.message }); } res.json({ success: true, message: `分片${chunkIndex}上传成功`, path: finalPath }); } catch (error) { console.error('处理上传分片请求出错:', error); res.status(500).json({ success: false, message: '服务器错误', error: error.toString() }); } });
app.post('/api/merge', async (req, res) => { try { console.log('收到合并分片请求:', req.body); const { fileHash, filename, size } = req.body; if (!fileHash) { return res.status(400).json({ success: false, message: '缺少必要参数: fileHash' }); } const ext = path.extname(filename); const chunkDir = path.resolve(TEMP_DIR, fileHash); const filePath = path.resolve(UPLOAD_DIR, `${fileHash}${ext}`); console.log('合并文件信息:', { chunkDir, filePath, filename, size, extension: ext }); if (!fs.existsSync(chunkDir)) { console.error(`分片目录不存在: ${chunkDir}`); try { const tempFiles = await fsPromises.readdir(TEMP_DIR); console.log('临时目录下的文件/目录:', tempFiles); } catch (err) { console.error('读取临时目录失败:', err); } return res.status(400).json({ success: false, message: '没有找到文件分片', detail: `分片目录 ${chunkDir} 不存在` }); } let chunks; try { chunks = await fsPromises.readdir(chunkDir); } catch (err) { console.error(`读取分片目录 ${chunkDir} 失败:`, err); return res.status(500).json({ success: false, message: '读取分片失败', error: err.message }); } if (chunks.length === 0) { console.error('分片目录为空'); return res.status(400).json({ success: false, message: '分片目录为空,无法合并' }); } console.log(`找到${chunks.length}个分片, 开始合并...`); chunks.sort((a, b) => parseInt(a) - parseInt(b)); const writeStream = fs.createWriteStream(filePath); let mergeSuccess = true; await new Promise((resolve, reject) => { writeStream.on('finish', () => { console.log('所有分片写入完成'); resolve(); }); writeStream.on('error', (err) => { console.error('写入文件错误:', err); mergeSuccess = false; reject(err); }); function writeChunk(index) { if (index >= chunks.length) { writeStream.end(); return; } const chunkPath = path.resolve(chunkDir, chunks[index]); console.log(`正在合并分片 ${chunks[index]}, 路径: ${chunkPath}`); if (!fs.existsSync(chunkPath)) { console.error(`分片文件不存在: ${chunkPath}`); writeChunk(index + 1); return; } const readStream = fs.createReadStream(chunkPath); readStream.on('end', () => { console.log(`分片 ${chunks[index]} 合并完成`); writeChunk(index + 1); }); readStream.on('error', (err) => { console.error(`读取分片 ${chunks[index]} 错误:`, err); writeChunk(index + 1); }); readStream.pipe(writeStream, { end: false }); } writeChunk(0); }); if (!mergeSuccess) { return res.status(500).json({ success: false, message: '合并分片过程中出错' }); } console.log('删除临时分片目录:', chunkDir); try { for (const chunk of chunks) { const chunkPath = path.resolve(chunkDir, chunk); if (fs.existsSync(chunkPath)) { await fsPromises.unlink(chunkPath); } } await fsPromises.rmdir(chunkDir); console.log('临时分片目录删除成功'); } catch (error) { console.error('删除临时分片目录失败:', error); } const fileInfo = { originalName: filename, size, extension: ext, uploadTime: new Date().toISOString() }; await fsPromises.writeFile( path.resolve(UPLOAD_DIR, `${fileHash}.json`), JSON.stringify(fileInfo, null, 2) ); console.log('文件合并成功:', filePath); res.json({ success: true, message: '文件合并成功', url: `/uploads/${fileHash}${ext}`, fileInfo }); } catch (error) { console.error('合并分片出错:', error); res.status(500).json({ success: false, message: error.message || '服务器错误', error: error.toString() }); } });
app.post('/api/clean', async (req, res) => { try { const dirs = await fsPromises.readdir(TEMP_DIR); console.log('待清理的目录:', dirs); for (const dir of dirs) { const dirPath = path.join(TEMP_DIR, dir); const stat = await fsPromises.stat(dirPath); if (stat.isDirectory()) { console.log(`清理目录: ${dirPath}`); try { const files = await fsPromises.readdir(dirPath); for (const file of files) { await fsPromises.unlink(path.join(dirPath, file)); } await fsPromises.rmdir(dirPath); console.log(`目录 ${dirPath} 已清理`); } catch (err) { console.error(`清理目录 ${dirPath} 时出错:`, err); } } } res.json({ success: true, message: '分片目录已清理' }); } catch (error) { console.error('清理分片目录出错:', error); res.status(500).json({ success: false, message: error.message }); } });
app.get('/api/files', async (req, res) => { try { const files = await fsPromises.readdir(UPLOAD_DIR); const fileList = []; for (const file of files) { if (file.endsWith('.json') || file.startsWith('.')) { continue; } try { const filePath = path.resolve(UPLOAD_DIR, file); const stat = await fsPromises.stat(filePath); const fileHash = path.basename(file).split('.')[0]; const metaFilePath = path.resolve(UPLOAD_DIR, `${fileHash}.json`); let metaData = {}; if (fs.existsSync(metaFilePath)) { const metaContent = await fsPromises.readFile(metaFilePath, 'utf8'); metaData = JSON.parse(metaContent); } fileList.push({ name: metaData.originalName || file, hash: fileHash, size: stat.size, uploadTime: metaData.uploadTime || stat.mtime.toISOString(), url: `/uploads/${file}`, type: metaData.extension || path.extname(file) || '未知' }); } catch (err) { console.error(`处理文件 ${file} 时出错:`, err); } } fileList.sort((a, b) => new Date(b.uploadTime).getTime() - new Date(a.uploadTime).getTime()); res.json({ success: true, files: fileList }); } catch (error) { console.error('获取文件列表出错:', error); res.status(500).json({ success: false, message: '获取文件列表失败', error: error.message }); } });
app.get('/api/download/:hash', async (req, res) => { try { const { hash } = req.params; const files = await fsPromises.readdir(UPLOAD_DIR); let targetFile = null; let metaData = null; for (const file of files) { if (file.startsWith(hash) && !file.endsWith('.json')) { targetFile = file; break; } } if (!targetFile) { return res.status(404).json({ success: false, message: '文件不存在' }); } try { const metaContent = await fsPromises.readFile( path.resolve(UPLOAD_DIR, `${hash}.json`), 'utf8' ); metaData = JSON.parse(metaContent); } catch (err) { console.warn(`未找到元数据文件 ${hash}.json:`, err); } const filePath = path.resolve(UPLOAD_DIR, targetFile); res.setHeader('Content-Disposition', `attachment; filename="${encodeURIComponent(metaData?.originalName || targetFile)}"`); res.setHeader('Content-Type', 'application/octet-stream'); const fileStream = fs.createReadStream(filePath); fileStream.pipe(res); } catch (error) { console.error('下载文件时出错:', error); res.status(500).json({ success: false, message: '下载文件失败', error: error.message }); } });
app.use('/uploads', express.static(UPLOAD_DIR));
app.use((err, req, res, next) => { console.error('服务器错误:', err); res.status(500).json({ success: false, message: '服务器内部错误', error: err.toString() }); });
app.use((req, res) => { console.log(`未找到路由: ${req.method} ${req.url}`); res.status(404).json({ success: false, message: '未找到请求的资源' }); });
const server = app.listen(port, () => { console.log('==========================================='); console.log(`大文件分片上传服务已启动: http://localhost:${port}`); console.log('上传目录信息:'); console.log(`- 主目录: ${UPLOAD_DIR}`); console.log(`- 临时目录: ${TEMP_DIR}`); console.log('API 路径:'); console.log(`- 检查文件: POST http://localhost:${port}/api/check`); console.log(`- 获取分片: GET http://localhost:${port}/api/uploaded/chunks?fileHash={hash}`); console.log(`- 上传分片: POST http://localhost:${port}/api/upload/chunk`); console.log(`- 合并文件: POST http://localhost:${port}/api/merge`); console.log(`- 访问文件: GET http://localhost:${port}/uploads/{hash}`); console.log('==========================================='); });
server.on('error', (error) => { console.error('服务器启动失败:', error); if (error.code === 'EADDRINUSE') { console.error(`端口 ${port} 已被占用,请尝试使用其他端口`); } process.exit(1); });
|