-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
710 lines (640 loc) · 24.8 KB
/
Copy pathserver.js
File metadata and controls
710 lines (640 loc) · 24.8 KB
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
const express = require('express');
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const os = require('os');
const QRCode = require('qrcode');
const app = express();
const PORT = 3000;
const UPLOAD_DIR = process.argv[2] ? path.resolve(process.argv[2]) : path.join(__dirname, 'uploads');
if (!fs.existsSync(UPLOAD_DIR)) {
fs.mkdirSync(UPLOAD_DIR, { recursive: true });
}
app.use(express.json());
function safePath(relativePath) {
const cleaned = path.normalize(relativePath).replace(/^(\.\.[\/\\])+/, '');
const resolved = path.resolve(UPLOAD_DIR, cleaned);
if (!resolved.startsWith(UPLOAD_DIR)) return null;
return resolved;
}
const TEMP_DIR = path.join(__dirname, '.tmp_uploads');
if (!fs.existsSync(TEMP_DIR)) fs.mkdirSync(TEMP_DIR, { recursive: true });
const storage = multer.diskStorage({
destination: (req, file, cb) => cb(null, TEMP_DIR),
filename: (req, file, cb) => cb(null, Date.now() + '-' + Math.random().toString(36).slice(2))
});
const upload = multer({
storage,
limits: { fileSize: 5 * 1024 * 1024 * 1024 }
});
function getLanIP() {
const interfaces = os.networkInterfaces();
for (const name of Object.keys(interfaces)) {
for (const iface of interfaces[name]) {
if (iface.family === 'IPv4' && !iface.internal) return iface.address;
}
}
return '127.0.0.1';
}
function formatSize(bytes) {
if (bytes === 0) return '0 B';
const k = 1024;
const sizes = ['B', 'KB', 'MB', 'GB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return (bytes / Math.pow(k, i)).toFixed(1) + ' ' + sizes[i];
}
function getDirSize(dirPath) {
let size = 0;
try {
const entries = fs.readdirSync(dirPath, { withFileTypes: true });
for (const entry of entries) {
const fullPath = path.join(dirPath, entry.name);
if (entry.isDirectory()) size += getDirSize(fullPath);
else size += fs.statSync(fullPath).size;
}
} catch (e) {}
return size;
}
function getDirFileCount(dirPath) {
let count = 0;
try {
const entries = fs.readdirSync(dirPath, { withFileTypes: true });
for (const entry of entries) {
const fullPath = path.join(dirPath, entry.name);
if (entry.isDirectory()) count += getDirFileCount(fullPath);
else count++;
}
} catch (e) {}
return count;
}
// API: list files
app.get('/api/files', (req, res) => {
try {
const relDir = req.query.dir || '';
const targetDir = relDir ? safePath(relDir) : UPLOAD_DIR;
if (!targetDir || !fs.existsSync(targetDir)) return res.json({ entries: [], currentDir: relDir });
const entries = fs.readdirSync(targetDir, { withFileTypes: true }).map(entry => {
const fullPath = path.join(targetDir, entry.name);
const stat = fs.statSync(fullPath);
const isDir = entry.isDirectory();
const size = isDir ? getDirSize(fullPath) : stat.size;
return {
name: entry.name,
isDir,
size,
sizeStr: formatSize(size),
fileCount: isDir ? getDirFileCount(fullPath) : 0,
time: stat.mtimeMs,
timeStr: new Date(stat.mtime).toLocaleString('zh-CN')
};
});
entries.sort((a, b) => {
if (a.isDir !== b.isDir) return a.isDir ? -1 : 1;
return b.time - a.time;
});
res.json({ entries, currentDir: relDir });
} catch (e) {
res.json({ entries: [], currentDir: '' });
}
});
// API: upload
app.post('/api/upload', upload.array('files', 500), (req, res) => {
try {
let paths = req.body.paths;
if (!paths) paths = [];
if (typeof paths === 'string') paths = [paths];
const currentDir = req.query.dir || '';
const destBase = currentDir ? safePath(currentDir) : UPLOAD_DIR;
if (!destBase) return res.status(400).json({ error: 'Invalid path' });
for (let i = 0; i < req.files.length; i++) {
const tempPath = req.files[i].path;
const relativePath = paths[i] || req.files[i].originalname;
const destPath = path.join(destBase, relativePath);
if (!destPath.startsWith(UPLOAD_DIR)) {
fs.unlinkSync(tempPath);
continue;
}
fs.mkdirSync(path.dirname(destPath), { recursive: true });
fs.renameSync(tempPath, destPath);
}
res.json({ success: true, count: req.files.length });
} catch (e) {
res.status(500).json({ error: e.message });
}
});
// API: download
app.get('/api/download/*', (req, res) => {
const relPath = req.params[0];
const filePath = safePath(relPath);
if (!filePath || !fs.existsSync(filePath)) {
return res.status(404).json({ error: 'Not found' });
}
const stat = fs.statSync(filePath);
if (stat.isDirectory()) {
return res.status(400).json({ error: 'Cannot download a directory' });
}
res.download(filePath, path.basename(filePath));
});
// API: delete
app.delete('/api/files/*', (req, res) => {
const relPath = req.params[0];
const filePath = safePath(relPath);
if (!filePath || !fs.existsSync(filePath)) {
return res.status(404).json({ error: 'Not found' });
}
const stat = fs.statSync(filePath);
if (stat.isDirectory()) {
fs.rmSync(filePath, { recursive: true, force: true });
} else {
fs.unlinkSync(filePath);
}
res.json({ success: true });
});
// API: mkdir
app.post('/api/mkdir', (req, res) => {
const { dir, name } = req.body;
const parentDir = dir ? safePath(dir) : UPLOAD_DIR;
if (!parentDir) return res.status(400).json({ error: 'Invalid path' });
const newDir = path.join(parentDir, name);
if (!newDir.startsWith(UPLOAD_DIR)) return res.status(400).json({ error: 'Invalid path' });
fs.mkdirSync(newDir, { recursive: true });
res.json({ success: true });
});
// API: QR code
app.get('/api/qrcode', async (req, res) => {
const url = `http://${getLanIP()}:${PORT}`;
const dataUrl = await QRCode.toDataURL(url, { width: 200, margin: 1 });
res.json({ url, qr: dataUrl });
});
// Main page
app.get('/', (req, res) => {
res.send(getHTML());
});
function getHTML() {
return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>LAN File Transfer</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
background: #f0f2f5; color: #333; min-height: 100vh;
}
.container { max-width: 860px; margin: 0 auto; padding: 20px; }
header { text-align: center; padding: 24px 0 16px; }
header h1 { font-size: 26px; color: #1a1a2e; margin-bottom: 6px; }
header p { color: #666; font-size: 14px; }
.lang-switch {
position: absolute; top: 16px; right: 20px;
display: flex; gap: 4px; background: #fff; border-radius: 8px;
padding: 3px; box-shadow: 0 2px 8px rgba(0,0,0,0.08);
}
.lang-btn {
padding: 5px 12px; border: none; border-radius: 6px; font-size: 13px;
cursor: pointer; background: transparent; color: #666; transition: all 0.15s;
}
.lang-btn.active { background: #4361ee; color: #fff; }
.lang-btn:hover:not(.active) { background: #f0f2f5; }
.info-bar {
display: flex; align-items: center; justify-content: center; gap: 20px;
background: #fff; border-radius: 12px; padding: 14px 24px; margin-bottom: 16px;
box-shadow: 0 2px 8px rgba(0,0,0,0.06);
}
.info-bar .url { font-size: 15px; font-weight: 600; color: #4361ee; font-family: monospace; }
.qr-toggle { cursor: pointer; color: #4361ee; font-size: 13px; text-decoration: underline; }
.qr-img { display: none; margin-top: 10px; }
.qr-img.show { display: block; }
.upload-zone {
border: 2px dashed #c5cae9; border-radius: 14px; padding: 32px 20px;
text-align: center; background: #fff; margin-bottom: 16px;
transition: all 0.2s; box-shadow: 0 2px 8px rgba(0,0,0,0.06);
}
.upload-zone:hover, .upload-zone.dragover { border-color: #4361ee; background: #f0f4ff; }
.upload-zone svg { width: 40px; height: 40px; margin-bottom: 10px; color: #4361ee; }
.upload-zone h3 { font-size: 16px; color: #333; margin-bottom: 4px; }
.upload-zone p { color: #888; font-size: 13px; }
.upload-zone input { display: none; }
.upload-btns { margin-top: 14px; display: flex; gap: 10px; justify-content: center; flex-wrap: wrap; }
.upload-btn {
padding: 8px 18px; border-radius: 8px; border: 1px solid #c5cae9;
background: #f8f9ff; color: #4361ee; font-size: 13px; font-weight: 500;
cursor: pointer; transition: all 0.15s;
}
.upload-btn:hover { background: #4361ee; color: #fff; border-color: #4361ee; }
.progress-bar { display: none; height: 6px; background: #e0e0e0; border-radius: 3px; margin: 12px 0; overflow: hidden; }
.progress-bar.show { display: block; }
.progress-bar .fill { height: 100%; background: linear-gradient(90deg, #4361ee, #7209b7); border-radius: 3px; transition: width 0.15s; width: 0%; }
.progress-text { display: none; text-align: center; font-size: 13px; color: #666; margin-bottom: 8px; }
.progress-text.show { display: block; }
.file-list { background: #fff; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.06); overflow: hidden; }
.file-list-header {
padding: 14px 20px; font-size: 15px; font-weight: 600;
border-bottom: 1px solid #eee; display: flex; justify-content: space-between; align-items: center;
}
.file-list-header span { color: #888; font-size: 13px; font-weight: 400; }
.breadcrumb {
padding: 10px 20px; background: #fafbff; border-bottom: 1px solid #eee;
font-size: 13px; display: flex; align-items: center; gap: 4px; flex-wrap: wrap;
}
.breadcrumb a {
color: #4361ee; text-decoration: none; cursor: pointer; padding: 2px 4px; border-radius: 4px;
}
.breadcrumb a:hover { background: #eef0ff; }
.breadcrumb .sep { color: #ccc; }
.breadcrumb .current { color: #333; font-weight: 500; }
.empty-msg { padding: 40px 20px; text-align: center; color: #aaa; font-size: 14px; }
.file-item {
display: flex; align-items: center; padding: 12px 20px;
border-bottom: 1px solid #f5f5f5; transition: background 0.15s;
}
.file-item:hover { background: #fafbff; }
.file-item:last-child { border-bottom: none; }
.file-icon {
width: 38px; height: 38px; border-radius: 10px; background: #eef0ff;
display: flex; align-items: center; justify-content: center;
margin-right: 12px; flex-shrink: 0; font-size: 17px;
}
.file-icon.dir { background: #fff3e0; cursor: pointer; }
.file-info { flex: 1; min-width: 0; }
.file-name {
font-size: 14px; font-weight: 500; white-space: nowrap;
overflow: hidden; text-overflow: ellipsis;
}
.file-name.dir-link { color: #4361ee; cursor: pointer; }
.file-name.dir-link:hover { text-decoration: underline; }
.file-meta { font-size: 12px; color: #999; margin-top: 2px; }
.file-actions { display: flex; gap: 6px; flex-shrink: 0; margin-left: 10px; }
.btn {
border: none; border-radius: 8px; padding: 7px 12px; font-size: 12px;
cursor: pointer; transition: all 0.15s; font-weight: 500;
}
.btn-dl { background: #4361ee; color: #fff; }
.btn-dl:hover { background: #3a56d4; }
.btn-del { background: #fee2e2; color: #ef4444; }
.btn-del:hover { background: #fecaca; }
.toast {
position: fixed; top: 20px; left: 50%;
transform: translateX(-50%) translateY(-100px);
background: #333; color: #fff; padding: 10px 22px; border-radius: 8px;
font-size: 14px; transition: transform 0.3s; z-index: 1000;
}
.toast.show { transform: translateX(-50%) translateY(0); }
@media (max-width: 600px) {
.container { padding: 12px; }
header h1 { font-size: 20px; }
.upload-zone { padding: 24px 14px; }
.file-actions { flex-direction: column; gap: 3px; }
.btn { padding: 5px 8px; font-size: 11px; }
.lang-switch { top: 10px; right: 10px; }
}
</style>
</head>
<body>
<div class="lang-switch">
<button class="lang-btn" onclick="setLang('en')" id="langBtnEn">EN</button>
<button class="lang-btn" onclick="setLang('zh')" id="langBtnZh">中文</button>
</div>
<div class="container">
<header>
<h1 data-i18n="title">LAN File Transfer</h1>
<p data-i18n="subtitle">Transfer files and folders between devices on the same network</p>
</header>
<div class="info-bar">
<div>
<span style="color:#888;font-size:13px;" data-i18n="address">Address: </span>
<span class="url" id="serverUrl">loading...</span>
<br>
<span class="qr-toggle" onclick="toggleQR()" data-i18n="showQR">Show QR Code</span>
<div class="qr-img" id="qrBox"><img id="qrImg" src="" alt="QR"></div>
</div>
</div>
<div class="upload-zone" id="dropZone">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
<polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/>
</svg>
<h3 data-i18n="dropTitle">Drag and drop files or folders here</h3>
<p data-i18n="dropHint">Files will be uploaded to the current directory</p>
<div class="upload-btns">
<button class="upload-btn" onclick="document.getElementById('fileInput').click()" data-i18n="selectFiles">Select Files</button>
<button class="upload-btn" onclick="document.getElementById('dirInput').click()" data-i18n="selectFolder">Select Folder</button>
</div>
<input type="file" id="fileInput" multiple>
<input type="file" id="dirInput" webkitdirectory mozdirectory directory multiple>
</div>
<div class="progress-bar" id="progressBar"><div class="fill" id="progressFill"></div></div>
<div class="progress-text" id="progressText"></div>
<div class="file-list">
<div class="file-list-header">
<span data-i18n="fileList" style="color:#333;font-size:15px;font-weight:600;">File List</span>
<span id="fileCount">0 items</span>
</div>
<div class="breadcrumb" id="breadcrumb"></div>
<div id="fileListBody">
<div class="empty-msg" data-i18n="empty">No files</div>
</div>
</div>
</div>
<div class="toast" id="toast"></div>
<script>
// ==================== i18n ====================
const I18N = {
en: {
title: 'LAN File Transfer',
subtitle: 'Transfer files and folders between devices on the same network',
address: 'Address: ',
showQR: 'Show QR Code',
hideQR: 'Hide QR Code',
dropTitle: 'Drag and drop files or folders here',
dropHint: 'Files will be uploaded to the current directory',
selectFiles: 'Select Files',
selectFolder: 'Select Folder',
fileList: 'File List',
empty: 'No files',
emptyDir: 'This directory is empty',
download: 'Download',
delete: 'Delete',
items: ' items',
files: ' files',
root: 'Root',
uploading: 'Uploading... ',
uploadDone: 'Upload complete!',
uploadSuccess: 'Upload successful!',
uploadFail: 'Upload failed',
deleted: 'Deleted',
confirmDeleteFile: 'Delete this file?',
confirmDeleteDir: 'Delete this folder and all its contents?',
folder: 'Folder',
},
zh: {
title: 'LAN File Transfer',
subtitle: '在局域网内的设备之间快速传输文件和文件夹',
address: '访问地址:',
showQR: '显示二维码',
hideQR: '隐藏二维码',
dropTitle: '拖拽文件或文件夹到此处上传',
dropHint: '上传到当前浏览的目录',
selectFiles: '选择文件',
selectFolder: '选择文件夹',
fileList: '文件列表',
empty: '暂无文件',
emptyDir: '此目录为空',
download: '下载',
delete: '删除',
items: ' 项',
files: ' 个文件',
root: '根目录',
uploading: '上传中... ',
uploadDone: '上传完成!',
uploadSuccess: '上传成功!',
uploadFail: '上传失败',
deleted: '已删除',
confirmDeleteFile: '确认删除此文件?',
confirmDeleteDir: '确认删除此文件夹及其所有内容?',
folder: '文件夹',
}
};
let currentLang = (navigator.language || '').startsWith('zh') ? 'zh' : 'en';
function t(key) { return I18N[currentLang][key] || I18N['en'][key] || key; }
function applyI18n() {
document.querySelectorAll('[data-i18n]').forEach(el => {
const key = el.getAttribute('data-i18n');
if (I18N[currentLang][key] !== undefined) {
el.textContent = I18N[currentLang][key];
}
});
// Update lang button active state
document.getElementById('langBtnEn').classList.toggle('active', currentLang === 'en');
document.getElementById('langBtnZh').classList.toggle('active', currentLang === 'zh');
}
function setLang(lang) {
currentLang = lang;
localStorage.setItem('lan-transfer-lang', lang);
applyI18n();
renderBreadcrumb();
loadFiles();
}
// ==================== Core ====================
let currentDir = '';
let qrVisible = false;
function showToast(msg) {
const el = document.getElementById('toast');
el.textContent = msg;
el.classList.add('show');
setTimeout(() => el.classList.remove('show'), 2500);
}
function getIcon(name, isDir) {
if (isDir) return '📂';
const ext = name.split('.').pop().toLowerCase();
const map = {
pdf:'📄',doc:'📝',docx:'📝',xls:'📊',xlsx:'📊',ppt:'📎',pptx:'📎',
jpg:'🖼️',jpeg:'🖼️',png:'🖼️',gif:'🖼️',svg:'🖼️',webp:'🖼️',
mp4:'🎬',avi:'🎬',mov:'🎬',mkv:'🎬',
mp3:'🎵',wav:'🎵',flac:'🎵',
zip:'📦',rar:'📦','7z':'📦',tar:'📦',gz:'📦',
js:'💻',ts:'💻',py:'💻',java:'💻',c:'💻',cpp:'💻',
txt:'📃',md:'📃',json:'📃',csv:'📃',
};
return map[ext] || '📄';
}
function renderBreadcrumb() {
const bc = document.getElementById('breadcrumb');
const parts = currentDir ? currentDir.split('/').filter(Boolean) : [];
let html = '<a onclick="navigateTo(\\'\\')">' + t('root') + '</a>';
let accumulated = '';
for (let i = 0; i < parts.length; i++) {
accumulated += (accumulated ? '/' : '') + parts[i];
const p = accumulated;
html += '<span class="sep">/</span>';
if (i === parts.length - 1) {
html += '<span class="current">' + parts[i] + '</span>';
} else {
html += '<a onclick="navigateTo(\\'' + p.replace(/'/g, "\\\\'") + '\\')">' + parts[i] + '</a>';
}
}
bc.innerHTML = html;
}
function navigateTo(dir) {
currentDir = dir;
renderBreadcrumb();
loadFiles();
}
async function loadFiles() {
const url = '/api/files' + (currentDir ? '?dir=' + encodeURIComponent(currentDir) : '');
const res = await fetch(url);
const data = await res.json();
const files = data.entries;
const body = document.getElementById('fileListBody');
document.getElementById('fileCount').textContent = files.length + t('items');
if (files.length === 0) {
body.innerHTML = '<div class="empty-msg">' + (currentDir ? t('emptyDir') : t('empty')) + '</div>';
return;
}
body.innerHTML = files.map(f => {
const relPath = currentDir ? currentDir + '/' + f.name : f.name;
const encodedPath = encodeURIComponent(relPath);
const escapedRelPath = relPath.replace(/'/g, "\\\\'");
return \`
<div class="file-item">
<div class="file-icon \${f.isDir ? 'dir' : ''}" \${f.isDir ? 'onclick="navigateTo(\\'' + escapedRelPath + '\\')"' : ''}>
\${getIcon(f.name, f.isDir)}
</div>
<div class="file-info">
<div class="file-name \${f.isDir ? 'dir-link' : ''}" \${f.isDir ? 'onclick="navigateTo(\\'' + escapedRelPath + '\\')"' : ''}>
\${f.name}
</div>
<div class="file-meta">
\${f.isDir ? f.fileCount + t('files') + ' · ' : ''}\${f.sizeStr} · \${f.timeStr}
</div>
</div>
<div class="file-actions">
\${f.isDir ? '' : '<button class="btn btn-dl" onclick="downloadItem(\\'' + encodedPath + '\\')">' + t('download') + '</button>'}
<button class="btn btn-del" onclick="deleteItem('\${encodedPath}', \${f.isDir})">\${t('delete')}</button>
</div>
</div>\`;
}).join('');
}
function fileListToEntries(fileList) {
const entries = [];
for (const file of fileList) {
const relativePath = file.webkitRelativePath || file.name;
entries.push({ file, relativePath });
}
return entries;
}
async function getDropEntries(dataTransfer) {
const entries = [];
async function readEntry(entry, basePath) {
if (entry.isFile) {
const file = await new Promise((resolve, reject) => entry.file(resolve, reject));
entries.push({ file, relativePath: basePath + file.name });
} else if (entry.isDirectory) {
const reader = entry.createReader();
let batch;
do {
batch = await new Promise((resolve, reject) => reader.readEntries(resolve, reject));
for (const child of batch) {
await readEntry(child, basePath + entry.name + '/');
}
} while (batch.length > 0);
}
}
const items = dataTransfer.items;
const topEntries = [];
for (let i = 0; i < items.length; i++) {
const entry = items[i].webkitGetAsEntry ? items[i].webkitGetAsEntry() : null;
if (entry) topEntries.push(entry);
}
for (const entry of topEntries) {
await readEntry(entry, '');
}
return entries;
}
function uploadFiles(fileEntries) {
const formData = new FormData();
for (const entry of fileEntries) {
formData.append('files', entry.file);
formData.append('paths', entry.relativePath);
}
const xhr = new XMLHttpRequest();
const progressBar = document.getElementById('progressBar');
const progressFill = document.getElementById('progressFill');
const progressText = document.getElementById('progressText');
progressBar.classList.add('show');
progressText.classList.add('show');
progressFill.style.width = '0%';
xhr.upload.onprogress = (e) => {
if (e.lengthComputable) {
const pct = Math.round(e.loaded / e.total * 100);
progressFill.style.width = pct + '%';
progressText.textContent = t('uploading') + pct + '% (' + fileEntries.length + (currentLang === 'zh' ? ' 个文件)' : ' files)');
}
};
xhr.onload = () => {
progressFill.style.width = '100%';
progressText.textContent = t('uploadDone');
setTimeout(() => { progressBar.classList.remove('show'); progressText.classList.remove('show'); }, 1500);
showToast(t('uploadSuccess'));
loadFiles();
};
xhr.onerror = () => {
progressBar.classList.remove('show');
progressText.classList.remove('show');
showToast(t('uploadFail'));
};
const dirParam = currentDir ? '?dir=' + encodeURIComponent(currentDir) : '';
xhr.open('POST', '/api/upload' + dirParam);
xhr.send(formData);
}
function downloadItem(encodedPath) {
window.open('/api/download/' + encodedPath, '_blank');
}
async function deleteItem(encodedPath, isDir) {
const msg = isDir ? t('confirmDeleteDir') : t('confirmDeleteFile');
if (!confirm(msg)) return;
await fetch('/api/files/' + encodedPath, { method: 'DELETE' });
showToast(t('deleted'));
loadFiles();
}
// Drag & Drop
const dropZone = document.getElementById('dropZone');
dropZone.addEventListener('dragover', (e) => { e.preventDefault(); dropZone.classList.add('dragover'); });
dropZone.addEventListener('dragleave', () => dropZone.classList.remove('dragover'));
dropZone.addEventListener('drop', async (e) => {
e.preventDefault();
dropZone.classList.remove('dragover');
if (e.dataTransfer.items && e.dataTransfer.items[0] && e.dataTransfer.items[0].webkitGetAsEntry) {
const entries = await getDropEntries(e.dataTransfer);
if (entries.length > 0) uploadFiles(entries);
} else if (e.dataTransfer.files.length) {
uploadFiles(fileListToEntries(e.dataTransfer.files));
}
});
document.getElementById('fileInput').addEventListener('change', function() {
if (this.files.length) uploadFiles(fileListToEntries(this.files));
this.value = '';
});
document.getElementById('dirInput').addEventListener('change', function() {
if (this.files.length) uploadFiles(fileListToEntries(this.files));
this.value = '';
});
function toggleQR() {
qrVisible = !qrVisible;
document.getElementById('qrBox').classList.toggle('show', qrVisible);
document.querySelector('[data-i18n="showQR"], [data-i18n="hideQR"]').textContent = qrVisible ? t('hideQR') : t('showQR');
document.querySelector('.qr-toggle').setAttribute('data-i18n', qrVisible ? 'hideQR' : 'showQR');
}
async function init() {
// Restore saved language
const saved = localStorage.getItem('lan-transfer-lang');
if (saved && I18N[saved]) currentLang = saved;
const res = await fetch('/api/qrcode');
const data = await res.json();
document.getElementById('serverUrl').textContent = data.url;
document.getElementById('qrImg').src = data.qr;
applyI18n();
renderBreadcrumb();
loadFiles();
}
init();
setInterval(loadFiles, 5000);
</script>
</body>
</html>`;
}
// Start server
app.listen(PORT, '0.0.0.0', () => {
const ip = getLanIP();
console.log('\\n========================================');
console.log(' LAN File Transfer Server');
console.log('========================================');
console.log(` Local: http://localhost:${PORT}`);
console.log(` LAN: http://${ip}:${PORT}`);
console.log(` Dir: ${UPLOAD_DIR}`);
console.log('========================================');
console.log(' Open the LAN address on any device in the same network');
console.log(' Ctrl+C to stop\\n');
});