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 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869
| const HTML = '<!DOCTYPE html>\n' + '<html lang="zh-CN">\n' + '<head>\n' + ' <meta charset="utf-8" />\n' + ' <meta name="viewport" content="width=device-width, initial-scale=1" />\n' + ' <title>✨ Air1 TempFile</title>\n' + ' <link rel="icon" type="image/png" href="https://air1.cn/favicon.png" />\n' + ' <style>\n' + ' :root {\n' + ' --bg: #0f0f12;\n' + ' --card-bg: rgba(255, 255, 255, 0.06);\n' + ' --card-border: rgba(255, 255, 255, 0.1);\n' + ' --text: #f0f0f5;\n' + ' --muted: #a0a0b0;\n' + ' --primary: #4d9fff;\n' + ' --success: #4ade80;\n' + ' --danger: #f87171;\n' + ' --shadow: 0 8px 32px rgba(0, 0, 0, 0.3);\n' + ' --radius: 18px;\n' + ' }\n' + '\n' + ' @media (prefers-color-scheme: light) {\n' + ' :root {\n' + ' --bg: #f8f9ff;\n' + ' --card-bg: rgba(255, 255, 255, 0.7);\n' + ' --card-border: rgba(0, 0, 0, 0.08);\n' + ' --text: #1a1a25;\n' + ' --muted: #666;\n' + ' --primary: #2563eb;\n' + ' --success: #16a34a;\n' + ' --danger: #dc2626;\n' + ' --shadow: 0 8px 24px rgba(0, 0, 0, 0.08);\n' + ' }\n' + ' }\n' + '\n' + ' * {\n' + ' margin: 0;\n' + ' padding: 0;\n' + ' box-sizing: border-box;\n' + ' }\n' + '\n' + ' body {\n' + ' background: var(--bg);\n' + ' color: var(--text);\n' + ' font-family: \'SF Pro Display\', -apple-system, BlinkMacSystemFont, \'Segoe UI\', sans-serif;\n' + ' min-height: 100vh;\n' + ' display: flex;\n' + ' flex-direction: column;\n' + ' align-items: center;\n' + ' justify-content: center;\n' + ' padding: 2rem 1.5rem;\n' + ' position: relative;\n' + ' overflow-x: hidden;\n' + ' }\n' + '\n' + ' body::before {\n' + ' content: "";\n' + ' position: absolute;\n' + ' top: 0;\n' + ' left: 0;\n' + ' width: 100%;\n' + ' height: 100%;\n' + ' background: \n' + ' radial-gradient(circle at 20% 30%, rgba(77, 159, 255, 0.06) 0%, transparent 40%),\n' + ' radial-gradient(circle at 80% 70%, rgba(77, 159, 255, 0.04) 0%, transparent 50%);\n' + ' pointer-events: none;\n' + ' z-index: -1;\n' + ' }\n' + '\n' + ' .container {\n' + ' width: 100%;\n' + ' max-width: 520px;\n' + ' text-align: center;\n' + ' }\n' + '\n' + ' h1 {\n' + ' font-weight: 700;\n' + ' font-size: 2.2rem;\n' + ' margin-bottom: 0.4rem;\n' + ' background: linear-gradient(135deg, #ffffff, #a0a0ff);\n' + ' -webkit-background-clip: text;\n' + ' background-clip: text;\n' + ' color: transparent;\n' + ' background-size: 200% 200%;\n' + ' animation: gradientShift 8s ease infinite;\n' + ' }\n' + '\n' + ' @keyframes gradientShift {\n' + ' 0% { background-position: 0% 50%; }\n' + ' 50% { background-position: 100% 50%; }\n' + ' 100% { background-position: 0% 50%; }\n' + ' }\n' + '\n' + ' .subtitle {\n' + ' color: var(--muted);\n' + ' font-size: 0.95rem;\n' + ' margin-bottom: 2.2rem;\n' + ' }\n' + '\n' + ' .upload-card {\n' + ' background: var(--card-bg);\n' + ' border: 1px solid var(--card-border);\n' + ' backdrop-filter: blur(12px);\n' + ' -webkit-backdrop-filter: blur(12px);\n' + ' border-radius: var(--radius);\n' + ' padding: 2.2rem 1.5rem;\n' + ' margin-bottom: 1.8rem;\n' + ' cursor: pointer;\n' + ' transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);\n' + ' position: relative;\n' + ' overflow: hidden;\n' + ' }\n' + '\n' + ' .upload-card:hover {\n' + ' transform: translateY(-4px);\n' + ' box-shadow: var(--shadow);\n' + ' border-color: rgba(77, 159, 255, 0.3);\n' + ' }\n' + '\n' + ' .upload-card.dragover {\n' + ' border-color: var(--primary);\n' + ' background: rgba(77, 159, 255, 0.08);\n' + ' }\n' + '\n' + ' .upload-icon {\n' + ' font-size: 3.2rem;\n' + ' margin-bottom: 1.2rem;\n' + ' display: block;\n' + ' transition: transform 0.3s;\n' + ' }\n' + '\n' + ' .upload-card:hover .upload-icon {\n' + ' transform: scale(1.1) rotate(3deg);\n' + ' }\n' + '\n' + ' .upload-text {\n' + ' font-size: 1.1rem;\n' + ' font-weight: 500;\n' + ' margin-bottom: 0.4rem;\n' + ' }\n' + '\n' + ' .upload-hint {\n' + ' font-size: 0.85rem;\n' + ' color: var(--muted);\n' + ' }\n' + '\n' + ' .selected-file {\n' + ' margin-top: 0.6rem;\n' + ' font-size: 0.85rem;\n' + ' color: var(--primary);\n' + ' display: none;\n' + ' }\n' + '\n' + ' #fileInput {\n' + ' display: none;\n' + ' }\n' + '\n' + ' .btn {\n' + ' width: 100%;\n' + ' padding: 0.95rem;\n' + ' background: var(--primary);\n' + ' color: white;\n' + ' border: none;\n' + ' border-radius: 14px;\n' + ' font-size: 1.05rem;\n' + ' font-weight: 600;\n' + ' cursor: pointer;\n' + ' transition: all 0.25s;\n' + ' letter-spacing: 0.3px;\n' + ' }\n' + '\n' + ' .btn:hover:not(:disabled) {\n' + ' background: #3a8bff;\n' + ' transform: translateY(-2px);\n' + ' box-shadow: 0 6px 16px rgba(77, 159, 255, 0.3);\n' + ' }\n' + '\n' + ' .btn:disabled {\n' + ' opacity: 0.7;\n' + ' cursor: not-allowed;\n' + ' transform: none;\n' + ' box-shadow: none;\n' + ' }\n' + '\n' + ' .result-card {\n' + ' background: var(--card-bg);\n' + ' border: 1px solid var(--card-border);\n' + ' backdrop-filter: blur(12px);\n' + ' -webkit-backdrop-filter: blur(12px);\n' + ' border-radius: var(--radius);\n' + ' padding: 1.6rem;\n' + ' margin-top: 1.5rem;\n' + ' display: none;\n' + ' }\n' + '\n' + ' .result-card.show {\n' + ' display: block;\n' + ' animation: fadeIn 0.4s ease;\n' + ' }\n' + '\n' + ' @keyframes fadeIn {\n' + ' from { opacity: 0; transform: translateY(10px); }\n' + ' to { opacity: 1; transform: translateY(0); }\n' + ' }\n' + '\n' + ' .result-title {\n' + ' font-size: 1.1rem;\n' + ' margin-bottom: 1rem;\n' + ' color: var(--success);\n' + ' font-weight: 600;\n' + ' }\n' + '\n' + ' .result-item {\n' + ' margin-bottom: 1rem;\n' + ' text-align: center;\n' + ' padding: 0.8rem;\n' + ' background: rgba(77, 159, 255, 0.05);\n' + ' border-radius: 10px;\n' + ' display: flex;\n' + ' flex-direction: column;\n' + ' align-items: center;\n' + ' }\n' + ' .result-filename {\n' + ' font-weight: bold;\n' + ' margin-bottom: 0.3rem;\n' + ' color: var(--text);\n' + ' }\n' + '\n' + ' .result-link {\n' + ' display: block;\n' + ' word-break: break-all;\n' + ' color: var(--primary);\n' + ' text-decoration: none;\n' + ' font-size: 0.9rem;\n' + ' font-family: monospace;\n' + ' margin: 0.2rem 0;\n' + ' }\n' + '\n' + ' .copy-btn {\n' + ' background: rgba(255, 255, 255, 0.12);\n' + ' color: var(--text);\n' + ' border: none;\n' + ' padding: 0.4rem 0.8rem;\n' + ' border-radius: 8px;\n' + ' font-weight: 600;\n' + ' cursor: pointer;\n' + ' transition: all 0.2s;\n' + ' font-size: 0.85rem;\n' + ' }\n' + '\n' + ' .copy-btn:hover {\n' + ' background: rgba(255, 255, 255, 0.2);\n' + ' }\n' + '\n' + ' .copy-btn.copied {\n' + ' background: var(--success);\n' + ' color: white;\n' + ' }\n' + '\n' + ' .error-msg {\n' + ' color: var(--danger);\n' + ' margin-top: 0.5rem;\n' + ' font-size: 0.85rem;\n' + ' }\n' + '\n' + ' .progress-track {\n' + ' height: 6px;\n' + ' background: rgba(255, 255, 255, 0.1);\n' + ' border-radius: 3px;\n' + ' margin-top: 1.2rem;\n' + ' overflow: hidden;\n' + ' }\n' + '\n' + ' .progress-fill {\n' + ' height: 100%;\n' + ' background: var(--primary);\n' + ' width: 0%;\n' + ' border-radius: 3px;\n' + ' transition: width 0.2s ease;\n' + ' }\n' + '\n' + ' .footer {\n' + ' margin-top: 2.5rem;\n' + ' color: var(--muted);\n' + ' font-size: 0.8rem;\n' + ' opacity: 0.8;\n' + ' }\n' + '\n' + ' @media (max-width: 480px) {\n' + ' h1 { font-size: 1.8rem; }\n' + ' .upload-card { padding: 1.8rem 1rem; }\n' + ' }\n' + ' </style>\n' + '</head>\n' + '<body>\n' + ' <div class="container">\n' + ' <h1>Air1 TempFile</h1>\n' + ' <p class="subtitle">安全上传 · 多文件自动打包 · 7天自动销毁</p>\n' + '\n' + ' <div class="upload-card" id="dropArea">\n' + ' <span class="upload-icon">📤</span>\n' + ' <p class="upload-text">拖拽文件或点击上传</p>\n' + ' <p class="upload-hint">支持任意格式</p>\n' + ' <p class="selected-file" id="selectedFile"></p>\n' + ' <input type="file" id="fileInput" multiple />\n' + ' </div>\n' + '\n' + ' <button class="btn" id="uploadBtn" onclick="uploadFiles()">确认上传</button>\n' + '\n' + ' <div class="progress-track" id="progressTrack" style="display:none;">\n' + ' <div class="progress-fill" id="progressFill"></div>\n' + ' </div>\n' + '\n' + ' <div class="result-card" id="resultCard">\n' + ' <div class="result-title">✅ 上传完成</div>\n' + ' <div id="resultsList"></div>\n' + ' </div>\n' + '\n' + ' <p class="footer">Part of <strong>Air1 Quick Tools</strong> · Powered by Cloudflare</p>\n' + ' </div>\n' + '\n' + ' <script>\n' + ' const dropArea = document.getElementById(\'dropArea\');\n' + ' const fileInput = document.getElementById(\'fileInput\');\n' + ' const uploadBtn = document.getElementById(\'uploadBtn\');\n' + ' const resultCard = document.getElementById(\'resultCard\');\n' + ' const resultsList = document.getElementById(\'resultsList\');\n' + ' const progressTrack = document.getElementById(\'progressTrack\');\n' + ' const progressFill = document.getElementById(\'progressFill\');\n' + ' const selectedFileEl = document.getElementById(\'selectedFile\');\n' + '\n' + ' [\'dragenter\', \'dragover\', \'dragleave\', \'drop\'].forEach(e => {\n' + ' dropArea.addEventListener(e, preventDefaults, false);\n' + ' });\n' + '\n' + ' function preventDefaults(e) {\n' + ' e.preventDefault();\n' + ' e.stopPropagation();\n' + ' }\n' + '\n' + ' [\'dragenter\', \'dragover\'].forEach(e => {\n' + ' dropArea.addEventListener(e, () => dropArea.classList.add(\'dragover\'), false);\n' + ' });\n' + '\n' + ' [\'dragleave\', \'drop\'].forEach(e => {\n' + ' dropArea.addEventListener(e, () => dropArea.classList.remove(\'dragover\'), false);\n' + ' });\n' + '\n' + ' dropArea.addEventListener(\'drop\', e => {\n' + ' fileInput.files = e.dataTransfer.files;\n' + ' fileInput.dispatchEvent(new Event(\'change\'));\n' + ' });\n' + '\n' + ' dropArea.addEventListener(\'click\', () => fileInput.click());\n' + '\n' + ' fileInput.addEventListener(\'change\', () => {\n' + ' const files = fileInput.files;\n' + ' if (files.length > 0) {\n' + ' let names = Array.from(files).map(f => f.name).join(\', \');\n' + ' if (names.length > 60) names = names.substring(0, 60) + \'...\';\n' + ' selectedFileEl.textContent = `已选择 ${files.length} 个文件:${names}`;\n' + ' selectedFileEl.style.display = \'block\';\n' + ' } else {\n' + ' selectedFileEl.style.display = \'none\';\n' + ' }\n' + ' });\n' + '\n' + ' async function uploadFiles() {\n' + ' const files = Array.from(fileInput.files);\n' + ' if (!files.length) return alert(\'请选择至少一个文件\');\n' + '\n' + ' for (const file of files) {\n' + ' if (file.size > 99 * 1024 * 1024) {\n' + ' return alert(`「${file.name}」不能超过 99MB`);\n' + ' }\n' + ' }\n' + '\n' + ' resultCard.classList.remove(\'show\');\n' + ' resultsList.innerHTML = \'\';\n' + ' uploadBtn.disabled = true;\n' + ' progressTrack.style.display = \'block\';\n' + ' progressFill.style.width = \'0%\';\n' + '\n' + ' const formData = new FormData();\n' + ' files.forEach(f => formData.append(\'file\', f));\n' + '\n' + ' try {\n' + ' const response = await fetch(\'/api/upload-public\', {\n' + ' method: \'POST\',\n' + ' body: formData,\n' + ' });\n' + '\n' + ' const res = await response.json();\n' + '\n' + ' if (response.ok && res.downloadUrl) {\n' + ' const div = document.createElement(\'div\');\n' + ' div.className = \'result-item\';\n' + ' let filename = files.length === 1 ? files[0].name : `upload_${res.fileId}.zip`;\n' + ' div.innerHTML = `\n' + ' <div class="result-filename">📁 ${filename}</div>\n' + ' <a class="result-link" href="${res.downloadUrl}" target="_blank">${res.downloadUrl}</a>\n' + ' <button class="copy-btn" onclick="copyText(event, \'${res.downloadUrl}\')">📋 复制</button>\n' + ' ${res.notifyError ? `<div class="error-msg">⚠️ 通知失败:${res.notifyError}</div>` : \'\'}\n' + ' `;\n' + ' resultsList.appendChild(div);\n' + ' resultCard.classList.add(\'show\');\n' + ' } else {\n' + ' alert(res.error || \'上传失败\');\n' + ' }\n' + ' } catch (e) {\n' + ' alert(\'网络错误,请重试\');\n' + ' } finally {\n' + ' uploadBtn.disabled = false;\n' + ' }\n' + ' }\n' + '\n' + ' // ====== 兼容性复制函数 ======\n' + ' function copyText(event, text) {\n' + ' if (navigator.clipboard && window.isSecureContext) {\n' + ' navigator.clipboard.writeText(text).then(() => {\n' + ' showCopySuccess(event.target);\n' + ' }).catch(() => {\n' + ' fallbackCopyText(event.target, text);\n' + ' });\n' + ' } else {\n' + ' fallbackCopyText(event.target, text);\n' + ' }\n' + ' }\n' + '\n' + ' function fallbackCopyText(btn, text) {\n' + ' const textarea = document.createElement(\'textarea\');\n' + ' textarea.value = text;\n' + ' textarea.style.position = \'fixed\';\n' + ' textarea.style.opacity = \'0\';\n' + ' document.body.appendChild(textarea);\n' + ' textarea.select();\n' + ' try {\n' + ' const ok = document.execCommand(\'copy\');\n' + ' if (ok) {\n' + ' showCopySuccess(btn);\n' + ' } else {\n' + ' alert(\'复制失败,请手动长按链接复制\');\n' + ' }\n' + ' } catch (e) {\n' + ' alert(\'复制失败,请手动复制\');\n' + ' } finally {\n' + ' document.body.removeChild(textarea);\n' + ' }\n' + ' }\n' + '\n' + ' function showCopySuccess(btn) {\n' + ' btn.classList.add(\'copied\');\n' + ' btn.textContent = \'✅ 已复制\';\n' + ' setTimeout(() => {\n' + ' btn.classList.remove(\'copied\');\n' + ' btn.textContent = \'📋 复制\';\n' + ' }, 2000);\n' + ' }\n' + ' </script>\n' + '</body>\n' + '</html>';
const MAX_TOTAL_SIZE = 50 * 1024 * 1024; const EXPIRATION_TTL = 7 * 24 * 3600;
async function generateFileId(env) { for (let i = 0; i < 5; i++) { const id = Math.random().toString(36).substring(2, 8); if (!(await env.TEMP_STORE.get(id))) { return id; } } return Math.random().toString(36).substring(2, 8) + Date.now().toString(36).slice(-2); }
function zipFiles(files) { const utf8Encoder = new TextEncoder(); const zip = []; let offset = 0; const centralDir = [];
for (const file of files) { const filenameBytes = utf8Encoder.encode(file.name); const header = new Uint8Array([ 0x50, 0x4b, 0x03, 0x04, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, file.data.byteLength & 0xff, (file.data.byteLength >> 8) & 0xff, (file.data.byteLength >> 16) & 0xff, (file.data.byteLength >> 24) & 0xff, filenameBytes.length & 0xff, (filenameBytes.length >> 8) & 0xff, 0x00, 0x00 ]);
const localFileHeader = new Uint8Array(header.length + filenameBytes.length); localFileHeader.set(header); localFileHeader.set(filenameBytes, header.length);
zip.push(localFileHeader, file.data);
const cdHeader = new Uint8Array([ 0x50, 0x4b, 0x01, 0x02, 0x14, 0x03, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, file.data.byteLength & 0xff, (file.data.byteLength >> 8) & 0xff, (file.data.byteLength >> 16) & 0xff, (file.data.byteLength >> 24) & 0xff, filenameBytes.length & 0xff, (filenameBytes.length >> 8) & 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, offset & 0xff, (offset >> 8) & 0xff, (offset >> 16) & 0xff, (offset >> 24) & 0xff ]); const centralRecord = new Uint8Array(cdHeader.length + filenameBytes.length); centralRecord.set(cdHeader); centralRecord.set(filenameBytes, cdHeader.length); centralDir.push(centralRecord);
offset += localFileHeader.length + file.data.byteLength; }
const totalEntries = files.length; const centralSize = centralDir.reduce((sum, d) => sum + d.length, 0); const eocd = new Uint8Array([ 0x50, 0x4b, 0x05, 0x06, 0x00, 0x00, 0x00, 0x00, totalEntries & 0xff, (totalEntries >> 8) & 0xff, totalEntries & 0xff, (totalEntries >> 8) & 0xff, centralSize & 0xff, (centralSize >> 8) & 0xff, (centralSize >> 16) & 0xff, (centralSize >> 24) & 0xff, offset & 0xff, (offset >> 8) & 0xff, (offset >> 16) & 0xff, (offset >> 24) & 0xff, 0x00, 0x00 ]);
const totalLength = zip.reduce((sum, part) => sum + part.length, 0) + centralSize + eocd.length; const finalZip = new Uint8Array(totalLength); let pos = 0; for (const part of zip) { finalZip.set(part, pos); pos += part.length; } for (const part of centralDir) { finalZip.set(part, pos); pos += part.length; } finalZip.set(eocd, pos);
return finalZip; }
async function sendWeComWebhookNotification(env, fileData) { const WEBHOOK_URL = env.WECOM_WEBHOOK_URL; if (!WEBHOOK_URL) return;
const { filename, size, downloadUrl } = fileData; let sizeText; if (size < 1024) sizeText = size + " B"; else if (size < 1024 * 1024) sizeText = (size / 1024).toFixed(2) + " KB"; else sizeText = (size / (1024 * 1024)).toFixed(2) + " MB";
const now = new Date().toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' }); const content = `📁 新文件上传\n\n文件名:${filename}\n大小:${sizeText}\n时间:${now}\n\n🔗 下载地址:\n${downloadUrl}`;
const payload = { msgtype: "text", text: { content } }; const resp = await fetch(WEBHOOK_URL, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload) });
const result = await resp.json(); if (result.errcode !== 0) { throw new Error(`Webhook 发送失败: ${result.errmsg}`); } }
export default { async fetch(request, env) { const url = new URL(request.url); const { pathname } = url;
if (pathname === "/") { return new Response(HTML, { headers: { "Content-Type": "text/html; charset=utf-8" } }); }
if (request.method === "OPTIONS") { return new Response(null, { headers: { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "POST, OPTIONS", "Access-Control-Allow-Headers": "Content-Type" } }); }
if (pathname === "/api/upload-public" && request.method === "POST") { const contentType = request.headers.get("content-type") || ""; if (!contentType.includes("multipart/form-data")) { return new Response(JSON.stringify({ error: "必须使用 multipart/form-data 上传" }), { status: 400, headers: { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*" } }); }
try { const formData = await request.formData(); const files = formData.getAll("file").filter(f => f instanceof File);
if (!files.length) { return new Response(JSON.stringify({ error: "未提供有效文件" }), { status: 400, headers: { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*" } }); }
for (const file of files) { if (file.size > 99 * 1024 * 1024) { return new Response(JSON.stringify({ error: `文件「${file.name}」超过 99MB` }), { status: 400, headers: { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*" } }); } }
const fileId = await generateFileId(env); let notifyError = null;
if (files.length === 1) { const file = files[0]; const buffer = await file.arrayBuffer(); const filename = file.name; const contentType = file.type || "application/octet-stream";
if (file.size <= 25 * 1024 * 1024) { await env.TEMP_STORE.put(fileId, buffer, { metadata: { filename, contentType, storage: "kv", isZip: false }, expirationTtl: EXPIRATION_TTL }); } else { const WEBDAV_BASE = 'https://higa.teracloud.jp/dav/air1/'; const credentials = btoa(`${env.WEBDAV_ACCOUNT}:${env.WEBDAV_PASSWORD}`); const webdavFilename = `file_${fileId}_${filename}`; const webdavUrl = WEBDAV_BASE + encodeURIComponent(webdavFilename);
const resp = await fetch(webdavUrl, { method: 'PUT', headers: { 'Authorization': `Basic ${credentials}`, 'Content-Type': contentType }, body: buffer });
if (!resp.ok) throw new Error(`WebDAV upload failed: ${resp.status}`);
await env.TEMP_STORE.put(fileId, "", { metadata: { filename, contentType, storage: "webdav", webdavFilename, isZip: false }, expirationTtl: EXPIRATION_TTL }); }
try { await sendWeComWebhookNotification(env, { filename, size: file.size, downloadUrl: `https://tmp.air1.cn/${fileId}` }); } catch (e) { notifyError = e.message; }
return new Response(JSON.stringify({ downloadUrl: `https://tmp.air1.cn/${fileId}`, fileId, notifyError }), { headers: { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*" } });
} else { let totalSize = 0; const fileBuffers = []; for (const file of files) { totalSize += file.size; const buffer = await file.arrayBuffer(); fileBuffers.push({ name: file.name, data: new Uint8Array(buffer) }); }
if (totalSize > MAX_TOTAL_SIZE) { return new Response(JSON.stringify({ error: `总大小不能超过 ${(MAX_TOTAL_SIZE / (1024*1024)).toFixed(1)}MB` }), { status: 400, headers: { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*" } }); }
const zipBuffer = zipFiles(fileBuffers); const zipSize = zipBuffer.byteLength; const zipName = `upload_${fileId}.zip`;
if (zipSize <= 25 * 1024 * 1024) { await env.TEMP_STORE.put(fileId, zipBuffer, { metadata: { filename: zipName, contentType: "application/zip", storage: "kv", isZip: true }, expirationTtl: EXPIRATION_TTL }); } else { const WEBDAV_BASE = 'https://higa.teracloud.jp/dav/air1/'; const credentials = btoa(`${env.WEBDAV_ACCOUNT}:${env.WEBDAV_PASSWORD}`); const webdavFilename = `zip_${fileId}.zip`; const webdavUrl = WEBDAV_BASE + encodeURIComponent(webdavFilename);
const resp = await fetch(webdavUrl, { method: 'PUT', headers: { 'Authorization': `Basic ${credentials}`, 'Content-Type': 'application/zip' }, body: zipBuffer });
if (!resp.ok) throw new Error(`WebDAV upload failed: ${resp.status}`);
await env.TEMP_STORE.put(fileId, "", { metadata: { filename: zipName, contentType: "application/zip", storage: "webdav", webdavFilename, isZip: true }, expirationTtl: EXPIRATION_TTL }); }
try { await sendWeComWebhookNotification(env, { filename: zipName, size: zipSize, downloadUrl: `https://tmp.air1.cn/${fileId}` }); } catch (e) { notifyError = e.message; }
return new Response(JSON.stringify({ downloadUrl: `https://tmp.air1.cn/${fileId}`, fileId, notifyError }), { headers: { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*" } }); }
} catch (e) { console.error("Upload error:", e); return new Response(JSON.stringify({ error: e.message || "服务器内部错误" }), { status: 500, headers: { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*" } }); } }
const segments = pathname.split('/').filter(Boolean); if (segments.length === 1 && segments[0].length === 6) { const id = segments[0]; const reservedPaths = new Set(['api', 'upload', 'f', 'favicon.ico', 'robots.txt', 'about', 's', 'webdav']); if (reservedPaths.has(id)) { return new Response("Reserved path", { status: 400 }); }
const entry = await env.TEMP_STORE.getWithMetadata(id, "arrayBuffer"); if (!entry?.metadata) { return new Response("File not found", { status: 404 }); }
const { storage, webdavFilename, filename, contentType } = entry.metadata;
if (storage === "kv") { return new Response(entry.value, { headers: { "Content-Type": contentType, "Content-Disposition": `attachment; filename="${encodeURIComponent(filename)}"`, "Cache-Control": "no-store" } }); }
if (storage === "webdav" && webdavFilename) { const WEBDAV_BASE = 'https://higa.teracloud.jp/dav/air1/'; const credentials = btoa(`${env.WEBDAV_ACCOUNT}:${env.WEBDAV_PASSWORD}`); const webdavUrl = WEBDAV_BASE + encodeURIComponent(webdavFilename);
let resp; try { resp = await fetch(webdavUrl, { headers: { 'Authorization': `Basic ${credentials}` } }); } catch (e) { return new Response("Storage unavailable", { status: 502 }); }
if (!resp.ok) { return new Response("File not found", { status: 404 }); }
const headers = new Headers({ "Content-Type": contentType, "Content-Disposition": `attachment; filename="${encodeURIComponent(filename)}"`, "Cache-Control": "no-store", "Access-Control-Allow-Origin": "*" });
return new Response(resp.body, { status: 200, headers }); }
return new Response("Invalid file record", { status: 500 }); }
return new Response("Not Found", { status: 404 }); } };
|