# 背景:

# 笨办法:

​ 我在经过无数次的尝试之后,发现无论我怎么操作,都存在一个问题,就是 git 无法成功推送到服务器,这个就很难办了,所以,个人感觉只有使用一个本办法才能操作了,如下:

​ 首先,老办法,将我们的 hexo 推送到 GitHub 上,之后等一会儿,能看了之后再说,

​ 然后,我们在目标服务器上运行以下代码(前提,创建一个 / Temp 目录):

1
2
3
4
5
6
7
cd /Temp/blog
rm -rf *
rm -rf /var/www/html/*
git clone https://github.com/g01den1/g01den1.github.io.git
mv ./g01den1.github.io/* /var/www/html/
cd /Temp/blog
rm -rf *

​ 最后,似乎只能通过这样的本办法来进行推送了,别的办法就没了,不过可能只是因为我太菜了,所以才导致了这个的问题,之后再解决吧。

# 似乎发现了个勉强可行的办法

​ 之前瞎几把倒腾 SpringBoot 的时候突然意识到似乎可以利用文件上传并解压,更何况 hexo 在生成网页之后,会产生一个 public 的文件夹,只需要本地打包之后,上传到自己写好的网站里,利用网站后端进行解压和移动,就可以完成 blog 的部署了,方法虽然还是有些笨,但确实已经很有效了。

​ 直接贴一个 SpringBoot 的项目代码:

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
package com.g01den.demo01.controller;

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import jakarta.servlet.http.HttpSession;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Stream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

@RestController
public class FileUploadController {

// 硬编码管理员账号密码
private static final String ADMIN_USER = "admin";
private static final String ADMIN_PASS = "146301";

private static final Map<String, String> TARGET_DIR_MAP = Map.of(
"blog1", "C:\\phpstudy_pro\\WWW\\blog1.g01den.top",
"blog2", "C:\\phpstudy_pro\\WWW\\blog2.g01den.top"
);

// ==================== 登录相关 ====================

@GetMapping("/admin")
public String adminLoginPage() {
return """
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=yes, viewport-fit=cover">
<title>管理员登录 · 安全验证</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}

body {
font-family: system-ui, 'Segoe UI', 'Noto Sans', -apple-system, BlinkMacSystemFont, 'Roboto', sans-serif;
background: linear-gradient(145deg, #f3f6fc 0%, #e9f0f8 100%);
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
padding: 1.5rem;
}

.login-wrapper {
width: 100%;
max-width: 420px;
}

.login-card {
background: rgba(255, 255, 255, 0.85);
backdrop-filter: blur(8px);
border-radius: 2.5rem;
padding: 2.5rem 2rem;
box-shadow: 0 20px 40px rgba(0, 0, 0, 0.04), 0 6px 12px rgba(0, 20, 40, 0.06);
border: 1px solid rgba(255, 255, 255, 0.7);
transition: transform 0.2s ease;
}

.login-header {
text-align: center;
margin-bottom: 2rem;
}

.login-header h2 {
font-size: 2rem;
font-weight: 600;
background: linear-gradient(135deg, #1e2b3c, #2c4c6e);
background-clip: text;
-webkit-background-clip: text;
color: transparent;
display: inline-flex;
align-items: center;
gap: 0.5rem;
}

.login-header h2::before {
content: "🔐";
font-size: 1.8rem;
background: none;
color: #3b6e9e;
}

.login-header p {
margin-top: 0.5rem;
color: #4a627a;
font-size: 0.9rem;
background: rgba(255, 255, 255, 0.6);
display: inline-block;
padding: 0.2rem 1rem;
border-radius: 30px;
backdrop-filter: blur(4px);
}

.form-group {
margin-bottom: 1.5rem;
}

label {
display: block;
margin-bottom: 0.5rem;
font-weight: 550;
color: #2c4c6e;
font-size: 0.95rem;
}

input {
width: 100%;
padding: 0.9rem 1.2rem;
font-size: 1rem;
background: rgba(255, 255, 255, 0.9);
border: 1.5px solid #d4e0ec;
border-radius: 3rem;
outline: none;
transition: all 0.2s;
color: #1e2f3f;
font-family: inherit;
}

input:focus {
border-color: #2c7cb6;
background: #ffffff;
box-shadow: 0 0 0 4px rgba(44, 124, 182, 0.1);
}

input::placeholder {
color: #9aafc4;
font-weight: 300;
}

.login-btn {
width: 100%;
padding: 0.9rem;
background: #2c7cb6;
color: white;
font-size: 1.1rem;
font-weight: 600;
border: none;
border-radius: 3rem;
cursor: pointer;
transition: all 0.2s ease;
box-shadow: 0 8px 18px rgba(44, 124, 182, 0.2);
margin-top: 0.5rem;
font-family: inherit;
letter-spacing: 0.3px;
}

.login-btn:hover {
background: #1e5a8b;
transform: translateY(-2px);
box-shadow: 0 12px 22px rgba(44, 124, 182, 0.25);
}

.login-btn:active {
transform: translateY(1px);
box-shadow: 0 4px 12px rgba(44, 124, 182, 0.2);
}

.back-link {
text-align: center;
margin-top: 1.8rem;
}

.back-link a {
color: #5c6f87;
text-decoration: none;
font-weight: 500;
padding: 0.5rem 1.2rem;
background: rgba(255, 255, 255, 0.5);
border-radius: 40px;
backdrop-filter: blur(4px);
transition: background 0.2s;
display: inline-block;
border: 1px solid rgba(255, 255, 255, 0.5);
}

.back-link a:hover {
background: rgba(255, 255, 255, 0.8);
color: #1e3b4f;
}

.error-message {
background: #fee8e8;
color: #c00;
text-align: center;
padding: 0.8rem;
border-radius: 40px;
margin-top: 1rem;
font-size: 0.9rem;
border: 1px solid #ffcdcd;
}

/* 移动端优化 */
@media (max-width: 480px) {
body {
padding: 1rem;
}
.login-card {
padding: 2rem 1.5rem;
border-radius: 2rem;
}
.login-header h2 {
font-size: 1.8rem;
}
input {
padding: 0.8rem 1.2rem;
}
}
</style>
</head>
<body>
<div class="login-wrapper">
<div class="login-card">
<div class="login-header">
<h2>管理员登录</h2>
<p>请验证身份以继续</p>
</div>

<form action="/admin" method="post">
<div class="form-group">
<label>📧 账号</label>
<input type="text" name="username" placeholder="请输入管理员账号" autocomplete="username" required>
</div>
<div class="form-group">
<label>🔒 密码</label>
<input type="password" name="password" placeholder="••••••••" autocomplete="current-password" required>
</div>
<button type="submit" class="login-btn">登 录</button>
</form>

<!-- 错误提示占位(如有需要可后端动态添加) -->
<!-- <div class="error-message">账号或密码错误</div> -->

<div class="back-link">
<a href="/">← 返回主页</a>
</div>
</div>
<div style="text-align: center; margin-top: 1.2rem; color: #7a92aa; font-size: 0.8rem;">
⚡ 安全入口 · 仅限授权访问
</div>
</div>
</body>
</html>
""";
}

@PostMapping("/admin")
public String handleLogin(@RequestParam("username") String username,
@RequestParam("password") String password,
HttpSession session) {
if (ADMIN_USER.equals(username) && ADMIN_PASS.equals(password)) {
session.setAttribute("user", username);
// 注意:每行开头的空白会被自动去除,此处使用缩进使代码整洁
return """
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=yes, viewport-fit=cover">
<title>登录成功 · 管理面板</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: system-ui, 'Segoe UI', 'Noto Sans', -apple-system, BlinkMacSystemFont, 'Roboto', sans-serif;
background: linear-gradient(145deg, #f3f6fc 0%, #e9f0f8 100%);
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
padding: 1.5rem;
}
.result-card {
background: rgba(255, 255, 255, 0.85);
backdrop-filter: blur(8px);
border-radius: 2.5rem;
padding: 2.5rem 2rem;
max-width: 450px;
width: 100%;
box-shadow: 0 20px 40px rgba(0, 0, 0, 0.04), 0 6px 12px rgba(0, 20, 40, 0.06);
border: 1px solid rgba(255, 255, 255, 0.7);
text-align: center;
}
.icon-success { font-size: 4rem; margin-bottom: 0.5rem; }
h2 {
font-size: 2rem;
font-weight: 600;
background: linear-gradient(135deg, #1e2b3c, #2c4c6e);
background-clip: text;
-webkit-background-clip: text;
color: transparent;
margin-bottom: 1rem;
}
.message { color: #2c4c6e; margin-bottom: 2rem; font-size: 1.05rem; line-height: 1.5; }
.action-buttons { display: flex; flex-direction: column; gap: 0.8rem; }
.btn {
display: block;
padding: 0.9rem 1.5rem;
border-radius: 3rem;
text-decoration: none;
font-weight: 550;
transition: all 0.2s ease;
border: 1.5px solid transparent;
}
.btn-primary {
background: #2c7cb6;
color: white;
box-shadow: 0 8px 18px rgba(44, 124, 182, 0.15);
}
.btn-primary:hover {
background: #1e5a8b;
transform: translateY(-2px);
box-shadow: 0 12px 22px rgba(44, 124, 182, 0.25);
}
.btn-secondary {
background: rgba(255, 255, 255, 0.7);
color: #2c4c6e;
border-color: #ccd7e4;
backdrop-filter: blur(4px);
}
.btn-secondary:hover {
background: rgba(255, 255, 255, 0.9);
border-color: #a0bbd4;
}
.footer-note { margin-top: 2rem; color: #6c819e; font-size: 0.85rem; }
@media (max-width: 480px) {
.result-card { padding: 2rem 1.5rem; }
h2 { font-size: 1.8rem; }
}
</style>
</head>
<body>
<div class="result-card">
<div class="icon-success">✅</div>
<h2>登录成功</h2>
<div class="message">
欢迎回来,<strong>""" + username + """
</strong>!<br>
您已通过身份验证,可以访问管理功能。
</div>
<div class="action-buttons">
<a href="/admin/novel/list" class="btn btn-primary">📚 进入小说管理</a>
<a href="/upload" class="btn btn-primary" style="background: #5a7ea0;">📝 博客部署页面</a>
<a href="/" class="btn btn-secondary">🏠 返回主页</a>
</div>
<div class="footer-note">
⚡ 会话已建立 · 安全访问
</div>
</div>
</body>
</html>
""";
} else {
return """
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=yes, viewport-fit=cover">
<title>登录失败 · 验证错误</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: system-ui, 'Segoe UI', 'Noto Sans', -apple-system, BlinkMacSystemFont, 'Roboto', sans-serif;
background: linear-gradient(145deg, #f3f6fc 0%, #e9f0f8 100%);
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
padding: 1.5rem;
}
.result-card {
background: rgba(255, 255, 255, 0.85);
backdrop-filter: blur(8px);
border-radius: 2.5rem;
padding: 2.5rem 2rem;
max-width: 450px;
width: 100%;
box-shadow: 0 20px 40px rgba(0, 0, 0, 0.04), 0 6px 12px rgba(0, 20, 40, 0.06);
border: 1px solid rgba(255, 255, 255, 0.7);
text-align: center;
}
.icon-error { font-size: 4rem; margin-bottom: 0.5rem; }
h2 {
font-size: 2rem;
font-weight: 600;
color: #c0392b;
margin-bottom: 1rem;
}
.error-message {
background: #fee8e8;
color: #b71c1c;
padding: 1rem;
border-radius: 2rem;
margin-bottom: 2rem;
font-weight: 500;
border: 1px solid #ffcdcd;
}
.action-buttons { display: flex; flex-direction: column; gap: 0.8rem; }
.btn {
display: block;
padding: 0.9rem 1.5rem;
border-radius: 3rem;
text-decoration: none;
font-weight: 550;
transition: all 0.2s ease;
border: 1.5px solid transparent;
}
.btn-primary {
background: #2c7cb6;
color: white;
box-shadow: 0 8px 18px rgba(44, 124, 182, 0.15);
}
.btn-primary:hover {
background: #1e5a8b;
transform: translateY(-2px);
}
.btn-secondary {
background: rgba(255, 255, 255, 0.7);
color: #2c4c6e;
border-color: #ccd7e4;
}
.btn-secondary:hover {
background: rgba(255, 255, 255, 0.9);
}
.footer-note { margin-top: 2rem; color: #6c819e; font-size: 0.85rem; }
@media (max-width: 480px) {
.result-card { padding: 2rem 1.5rem; }
h2 { font-size: 1.8rem; }
}
</style>
</head>
<body>
<div class="result-card">
<div class="icon-error">❌</div>
<h2>登录失败</h2>
<div class="error-message">
账号或密码错误,请重试。
</div>
<div class="action-buttons">
<a href="/admin" class="btn btn-primary">🔐 重新登录</a>
<a href="/" class="btn btn-secondary">🏠 返回主页</a>
</div>
<div class="footer-note">
⚡ 如忘记密码,请联系系统管理员
</div>
</div>
</body>
</html>
""";
}
}

// ==================== 上传功能 ====================

@GetMapping("/upload")
public String uploadForm(HttpSession session) {
// 登录检查
if (session.getAttribute("user") == null) {
return """
<!DOCTYPE html>
<html>
<head><meta charset="UTF-8"><title>未授权</title></head>
<body>
<h2>请先登录</h2>
<p>您需要管理员权限才能访问此页面。</p>
<p><a href="/admin">前往登录</a> | <a href="/">返回主页</a></p>
</body>
</html>
""";
}

return """
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>网站包上传部署</title>
<style>
body { font-family: Arial; margin: 50px; }
.container { max-width: 500px; margin: auto; padding: 20px; border: 1px solid #ccc; border-radius: 8px; }
.form-group { margin-bottom: 15px; }
label { display: block; margin-bottom: 5px; font-weight: bold; }
input[type="file"], select { width: 100%; padding: 8px; margin-top: 5px; }
button { background-color: #007bff; color: white; padding: 10px 20px; border: none; border-radius: 4px; cursor: pointer; }
button:hover { background-color: #0056b3; }
.error { color: red; }
.success { color: green; }
</style>
</head>
<body>
<div class="container">
<h2>上传ZIP包并部署到网站目录</h2>
<form action="/upload" method="post" enctype="multipart/form-data" id="uploadForm">
<div class="form-group">
<label>选择目标网站:</label>
<select name="option" required>
<option value="">--请选择--</option>
<option value="blog1">blog1.g01den.top</option>
<option value="blog2">blog2.g01den.top</option>
</select>
</div>
<div class="form-group">
<label>上传ZIP压缩包:</label>
<input type="file" name="file" accept=".zip,.ZIP" required>
</div>
<button type="submit">立即部署</button>
</form>
<div id="message" style="margin-top: 20px;"></div>
</div>
<script>
document.getElementById('uploadForm').onsubmit = async (e) => {
e.preventDefault();
const formData = new FormData(e.target);
const msgDiv = document.getElementById('message');
msgDiv.innerHTML = '<p>正在处理,请稍候...</p>';
try {
const response = await fetch('/upload', {
method: 'POST',
body: formData
});
const text = await response.text();
if (response.ok) {
msgDiv.innerHTML = '<p class="success">' + text + '</p>';
} else {
msgDiv.innerHTML = '<p class="error">错误:' + text + '</p>';
}
} catch (err) {
msgDiv.innerHTML = '<p class="error">请求失败:' + err.message + '</p>';
}
};
</script>
</body>
</html>
""";
}

@PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public String handleUpload(@RequestParam("file") MultipartFile file,
@RequestParam("option") String option,
HttpSession session) {
// 登录检查
if (session.getAttribute("user") == null) {
return "未授权访问,请先登录";
}

if (file.isEmpty()) return "错误:未选择文件";
if (!TARGET_DIR_MAP.containsKey(option)) return "错误:无效的选项";
String originalFilename = file.getOriginalFilename();
if (originalFilename == null || !originalFilename.toLowerCase().endsWith(".zip")) {
return "错误:只允许上传ZIP格式的文件";
}

Path targetDir = Paths.get(TARGET_DIR_MAP.get(option));
File tempZipFile = null;
AtomicInteger fileCount = new AtomicInteger(0);

try {
tempZipFile = File.createTempFile("upload_", ".zip");
file.transferTo(tempZipFile);
System.out.println("[INFO] 临时ZIP文件: " + tempZipFile.getAbsolutePath());

clearDirectory(targetDir);
System.out.println("[INFO] 已清空目标目录: " + targetDir);

fileCount.set(extractAndCopyAll(tempZipFile.toPath(), targetDir));

Files.deleteIfExists(tempZipFile.toPath());

return String.format("部署成功!共复制 %d 个文件/目录到 %s", fileCount.get(), targetDir.toString());

} catch (IllegalArgumentException e) {
return "错误:" + e.getMessage();
} catch (IOException e) {
e.printStackTrace();
return "错误:文件处理失败 - " + e.getMessage();
} catch (Exception e) {
e.printStackTrace();
return "错误:服务器内部异常 - " + e.getMessage();
} finally {
if (tempZipFile != null && tempZipFile.exists()) {
try {
Files.deleteIfExists(tempZipFile.toPath());
} catch (IOException ignored) {}
}
}
}

private void clearDirectory(Path dir) throws IOException {
if (!Files.exists(dir)) {
Files.createDirectories(dir);
return;
}
if (!Files.isDirectory(dir)) {
throw new IllegalArgumentException("路径不是目录: " + dir);
}
try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
for (Path entry : stream) {
deleteRecursively(entry);
}
}
}

private void deleteRecursively(Path path) throws IOException {
if (Files.isDirectory(path)) {
try (DirectoryStream<Path> stream = Files.newDirectoryStream(path)) {
for (Path entry : stream) {
deleteRecursively(entry);
}
}
}
Files.delete(path);
System.out.println("[DELETE] " + path);
}

private int extractAndCopyAll(Path zipPath, Path targetDir) throws IOException {
Path tempExtractDir = Files.createTempDirectory("zip_extract_");
System.out.println("[INFO] 临时解压目录: " + tempExtractDir);
try {
unzipWithGBK(zipPath, tempExtractDir);
System.out.println("[INFO] 解压完成,临时目录结构:");
printTree(tempExtractDir, 0);

// 智能决定要复制的源目录:如果解压根目录下只有一个子目录且没有其他文件,则进入该子目录
Path sourceDir = tempExtractDir;
try (DirectoryStream<Path> stream = Files.newDirectoryStream(tempExtractDir)) {
List<Path> children = new ArrayList<>();
for (Path child : stream) {
children.add(child);
}
if (children.size() == 1 && Files.isDirectory(children.get(0))) {
sourceDir = children.get(0);
System.out.println("[INFO] 检测到外层文件夹,自动进入: " + sourceDir);
}
}

// 可选:查找 index.html 位置,仅用于日志
Path indexHtml = findIndexHtml(sourceDir);
if (indexHtml != null) {
System.out.println("[INFO] 找到 index.html: " + indexHtml);
} else {
System.out.println("[WARN] 未找到 index.html,仍将复制全部文件");
}

int count = copyAll(sourceDir, targetDir);
System.out.println("[INFO] 复制完成,共 " + count + " 个条目");

System.out.println("[INFO] 目标目录最终内容:");
printTree(targetDir, 0);

return count;
} finally {
deleteRecursively(tempExtractDir);
}
}

private void unzipWithGBK(Path zipPath, Path destDir) throws IOException {
try (ZipFile zipFile = new ZipFile(zipPath.toFile(), Charset.forName("GBK"))) {
Enumeration<? extends ZipEntry> entries = zipFile.entries();
byte[] buffer = new byte[8192];
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
Path target = destDir.resolve(entry.getName()).normalize();
if (!target.startsWith(destDir)) {
throw new IOException("非法ZIP路径: " + entry.getName());
}
if (entry.isDirectory()) {
Files.createDirectories(target);
} else {
Files.createDirectories(target.getParent());
try (InputStream in = zipFile.getInputStream(entry);
OutputStream out = Files.newOutputStream(target)) {
int len;
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
}
}
System.out.println("[UNZIP] " + entry.getName());
}
}
}

private Path findIndexHtml(Path root) throws IOException {
try (Stream<Path> stream = Files.walk(root)) {
return stream.filter(Files::isRegularFile)
.filter(p -> p.getFileName().toString().equalsIgnoreCase("index.html"))
.findFirst()
.orElse(null);
}
}

private int copyAll(Path srcRoot, Path destRoot) throws IOException {
AtomicInteger counter = new AtomicInteger(0);
Files.walkFileTree(srcRoot, new SimpleFileVisitor<>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
Path relative = srcRoot.relativize(dir);
if (!relative.toString().isEmpty()) {
Path targetDir = destRoot.resolve(relative);
if (!Files.exists(targetDir)) {
Files.createDirectories(targetDir);
System.out.println("[COPY DIR] " + relative);
counter.incrementAndGet();
}
}
return FileVisitResult.CONTINUE;
}

@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Path relative = srcRoot.relativize(file);
Path targetFile = destRoot.resolve(relative);
Files.createDirectories(targetFile.getParent());
Files.copy(file, targetFile, StandardCopyOption.REPLACE_EXISTING);
System.out.println("[COPY FILE] " + relative);
counter.incrementAndGet();
return FileVisitResult.CONTINUE;
}
});
return counter.get();
}

private void printTree(Path dir, int depth) throws IOException {
String indent = " ".repeat(depth);
try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
for (Path entry : stream) {
if (Files.isDirectory(entry)) {
System.out.println(indent + "[D] " + entry.getFileName());
printTree(entry, depth + 1);
} else {
System.out.println(indent + "[F] " + entry.getFileName());
}
}
}
}
}

​ maven 打包成 jar 包之后就可以直接用了,之后甚至还可以写一个 python 或者 shell 之类的脚本,指定这俩 public 文件夹进行自动化压缩和上传:

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
from requests import post
import os
import zipfile

login_url = "http://upload.g01den.top/admin"
upload_url = "http://upload.g01den.top/upload"
login_data = {
"password": 146301,
"username": "admin"
}

def zipDir(dirpath, zipfilename):
zip = zipfile.ZipFile(zipfilename, 'w', zipfile.ZIP_DEFLATED)
for path, dirnames, filenames in os.walk(dirpath):
fpath = path.replace(dirpath, '')
for filename in filenames:
zip.write(os.path.join(path, filename), os.path.join(fpath, filename))
zip.close()

def get_cookie(url):
login_resp = post(url, data=login_data)
return login_resp.cookies

def upload_blog(url, cookie, zip_file, option):
resp = post(url,
files={"file": open(zip_file, "rb")},
cookies=cookie,
data={"option": option})
print(resp.text)

if __name__ == "__main__":
# ========== 新增控制变量 ==========
mode = 1 # 非交互模式:1=hexo1, 2=hexo2, 3=两者都上传
interactive = 1 # 1=交互式手动选择(此时mode失效),2=使用mode的值
# =================================

# ---- 定义两组配置 ----
configs = [
{
"input": "D:\\c\\blogs\\hexo1\\public",
"output": "D:\\c\\blogs\\hexo1\\public.zip",
"option": "blog1"
},
{
"input": "D:\\c\\blogs\\hexo2\\public",
"output": "D:\\c\\blogs\\hexo2\\public.zip",
"option": "blog1"
}
]

# ---- 决定最终选择 ----
if interactive == 1:
print("\n请选择要上传的博客:")
print("1: 主博客 (blog1)")
print("2: 副博客 (blog2)")
print("3: 全部上传")
choice = input("请输入数字 (1/2/3): ").strip()
while choice not in ('1', '2', '3'):
choice = input("输入无效,请重新输入 (1/2/3): ").strip()
choice = int(choice)
else:
choice = mode
if choice not in (1, 2, 3):
print(f"错误:mode 的值必须为 1、2 或 3,当前为 {choice}")
exit(1)

# ---- 登录获取 cookie ----
cookie = get_cookie(login_url)
print("获得 cookie 成功")

# ---- 根据 choice 执行压缩和上传 ----
indices = [0] if choice == 1 else [1] if choice == 2 else [0, 1]

for idx in indices:
cfg = configs[idx]
input_path = cfg["input"]
output_path = cfg["output"]
zip_file = output_path # 压缩后即得到该文件
option = cfg["option"]

# 压缩
zipDir(input_path, output_path)
print(f"打包 {input_path} 成功")

# 上传
print(f"开始上传 {option} 时间较长,请耐心等待...")
upload_blog(upload_url, cookie, zip_file, option)
print(f"上传 {option} 成功\n")

os.remove(zip_file)
print(f"删除 {zip_file} 成功\n")

​ 记得在部署的时候修改对应在本地的地址,之后才可以进行运行。

# 打包:

​ python 代码写出来之后,还有一件事,需要完成,就是对这个程序进行打包运行,

# 安装 PyInstaller:

1
pip install pyinstaller

# 执行打包命令

1
pyinstaller --onefile your_script.py
  • 命令解释pyinstaller --onefile 是基础命令。执行后,PyInstaller 会开始分析你的代码和所有依赖。
  • 输出位置:打包成功后,生成的 .exe 文件会出现在新创建的 dist 文件夹里。
  • 其他有用参数:
    • --windowed-w :如果你的程序有图形界面(比如用 Tkinter),加上这个参数可以隐藏背后的命令行黑窗口。
    • --icon=myicon.ico :为你的 .exe 文件指定一个图标。
    • --name=我的程序 :自定义生成的 .exe 文件名。

# 测试与分发

dist 文件夹里生成的 .exe 文件直接发给其他人即可。注意:PyInstaller 生成的 .exe 只能在同版本的 Windows 系统上运行。