feat: batch download
This commit is contained in:
@@ -52,6 +52,7 @@ curl -F "file=@report.pdf" http://localhost:8080/upload
|
||||
| POST | `/upload` | 上传文件(`multipart/form-data`,字段名 `file`) |
|
||||
| GET | `/files` | 列出当前未过期文件 |
|
||||
| GET | `/download/:filename` | 下载文件 |
|
||||
| POST | `/download-zip` | 批量下载 (body: `{"files":[...]}`, 最多 100 项) |
|
||||
| DELETE | `/files/:filename` | 删除文件 |
|
||||
|
||||
---
|
||||
@@ -60,19 +61,21 @@ curl -F "file=@report.pdf" http://localhost:8080/upload
|
||||
|
||||
```text
|
||||
tmp-upload/
|
||||
├── main.go # 入口、配置、路由注册 (60 行)
|
||||
├── embed.go # //go:embed + init() 拼接 (29 行)
|
||||
├── main.go # 入口、配置、路由注册 (61 行)
|
||||
├── embed.go # //go:embed + init() 拼接 (38 行)
|
||||
├── audit.go # 审计日志子系统 (102 行)
|
||||
├── quota.go # 配额管理 + formatSize (112 行)
|
||||
├── handlers.go # HTTP handlers + DTOs (296 行)
|
||||
├── handlers.go # HTTP handlers + DTOs (440 行)
|
||||
├── cleaner.go # TTL 过期清理 (57 行)
|
||||
├── audit_test.go # audit 单元测试
|
||||
├── security_test.sh # HTTP 端到端测试
|
||||
├── go.mod / go.sum
|
||||
└── static/
|
||||
├── index.html.tpl # HTML 骨架 (含 /*EMBED_CSS*/、/*EMBED_JS*/ 占位符)
|
||||
├── app.css # CSS (327 行)
|
||||
└── app.js # JS (486 行)
|
||||
├── app.css # CSS (357 行)
|
||||
├── app.js # JS — 主程序 (441 行)
|
||||
├── helpers.js # JS — 纯函数 + 倒计时 (58 行)
|
||||
└── batch.js # JS — 批量选择 / 批量下载 (87 行)
|
||||
```
|
||||
|
||||
### 单文件部署说明
|
||||
|
||||
@@ -17,6 +17,12 @@ var appCSS []byte
|
||||
//go:embed static/app.js
|
||||
var appJS []byte
|
||||
|
||||
//go:embed static/helpers.js
|
||||
var helpersJS []byte
|
||||
|
||||
//go:embed static/batch.js
|
||||
var batchJS []byte
|
||||
|
||||
// pageHTML is the assembled single-file deployment response.
|
||||
// Computed once at startup; same bytes served on every GET /.
|
||||
var pageHTML []byte
|
||||
@@ -24,6 +30,9 @@ var pageHTML []byte
|
||||
func init() {
|
||||
s := string(indexTpl)
|
||||
s = strings.Replace(s, "/*EMBED_CSS*/", string(appCSS), 1)
|
||||
s = strings.Replace(s, "/*EMBED_JS*/", string(appJS), 1)
|
||||
// JS 顺序敏感: app 先声明 consts / 注册 handlers; helpers 后注入纯函数;
|
||||
// batch 最后使用 consts 并启动 boot. 同 <script> 内共享顶层 var.
|
||||
combined := string(appJS) + "\n" + string(helpersJS) + "\n" + string(batchJS)
|
||||
s = strings.Replace(s, "/*EMBED_JS*/", combined, 1)
|
||||
pageHTML = []byte(s)
|
||||
}
|
||||
|
||||
+150
-6
@@ -1,7 +1,9 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
@@ -24,6 +26,19 @@ type fileResponse struct {
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
}
|
||||
|
||||
// validateFilename 从 URL/JSON 参数提取并校验 filename.
|
||||
// 返回 (sanitized, true) 表示安全可访问, 否则返回 ("", false).
|
||||
// 规则与 downloadHandler 原内联逻辑一致: filepath.Base + 拒绝 "" / "." / ".."
|
||||
// + 拒绝含 "/" "\" NUL 的名字 (后者同时兜住 Windows 路径).
|
||||
func validateFilename(raw string) (string, bool) {
|
||||
name := filepath.Base(raw)
|
||||
if name == "" || name == "." || name == ".." ||
|
||||
strings.ContainsAny(name, "/\\\x00") {
|
||||
return "", false
|
||||
}
|
||||
return name, true
|
||||
}
|
||||
|
||||
func uploadHandler(c *gin.Context) {
|
||||
f, err := c.FormFile(fieldName)
|
||||
if err != nil {
|
||||
@@ -164,9 +179,8 @@ func uniqueFilename(dir, original string) string {
|
||||
|
||||
func downloadHandler(c *gin.Context) {
|
||||
raw := c.Param("filename")
|
||||
name := filepath.Base(raw)
|
||||
if name == "" || name == "." || name == ".." ||
|
||||
strings.ContainsAny(name, "/\\\x00") {
|
||||
name, ok := validateFilename(raw)
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid filename"})
|
||||
audit(c, "download", gin.H{"file": raw, "result": "invalid_filename"})
|
||||
return
|
||||
@@ -257,9 +271,8 @@ func listHandler(c *gin.Context) {
|
||||
|
||||
func deleteHandler(c *gin.Context) {
|
||||
raw := c.Param("filename")
|
||||
name := filepath.Base(raw)
|
||||
if name == "" || name == "." || name == ".." ||
|
||||
strings.ContainsAny(name, "/\\\x00") {
|
||||
name, ok := validateFilename(raw)
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid filename"})
|
||||
audit(c, "delete", gin.H{"file": raw, "result": "invalid_filename"})
|
||||
return
|
||||
@@ -294,3 +307,134 @@ func deleteHandler(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"deleted": name})
|
||||
audit(c, "delete", gin.H{"file": name, "size": info.Size(), "result": "ok"})
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
// 批量下载: POST /download-zip (body: {"files":[...]} 或 query ?files=a&files=b)
|
||||
// 流式 archive/zip 输出, 不写临时文件. 缺失/路径非法/超量统一 4xx 兜底.
|
||||
// -----------------------------------------------------------------------------
|
||||
|
||||
const (
|
||||
batchMaxFiles = 100
|
||||
batchNameLimit = 200
|
||||
)
|
||||
|
||||
type batchRequest struct {
|
||||
Files []string `json:"files"`
|
||||
}
|
||||
|
||||
func batchDownloadHandler(c *gin.Context) {
|
||||
// 1. 收集 filenames: body JSON 优先, fallback 到 query ?files=
|
||||
var req batchRequest
|
||||
var names []string
|
||||
if c.Request.ContentLength > 0 && strings.HasPrefix(c.GetHeader("Content-Type"), "application/json") {
|
||||
if err := c.ShouldBindJSON(&req); err == nil && len(req.Files) > 0 {
|
||||
names = req.Files
|
||||
}
|
||||
}
|
||||
if names == nil {
|
||||
names = c.QueryArray("files")
|
||||
}
|
||||
if len(names) == 0 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "no files specified"})
|
||||
audit(c, "batch_download", gin.H{"result": "no_files"})
|
||||
return
|
||||
}
|
||||
if len(names) > batchMaxFiles {
|
||||
c.JSON(http.StatusBadRequest, gin.H{
|
||||
"error": fmt.Sprintf("too many files (max %d)", batchMaxFiles),
|
||||
})
|
||||
audit(c, "batch_download", gin.H{
|
||||
"count": len(names), "result": "too_many",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// 2. 校验每个文件名, 检查存在性
|
||||
type entry struct {
|
||||
path string
|
||||
size int64
|
||||
}
|
||||
var packed []entry
|
||||
miss := []string{} // 非 nil, JSON 输出 [] 而非 null
|
||||
for _, raw := range names {
|
||||
if len(raw) > batchNameLimit {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "filename too long (max 200 bytes)"})
|
||||
audit(c, "batch_download", gin.H{
|
||||
"count": len(names), "result": "too_long",
|
||||
})
|
||||
return
|
||||
}
|
||||
name, ok := validateFilename(raw)
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid filename: " + raw})
|
||||
audit(c, "batch_download", gin.H{
|
||||
"file": raw, "result": "invalid_filename",
|
||||
})
|
||||
return
|
||||
}
|
||||
p := filepath.Join(*uploadDir, name)
|
||||
info, err := os.Stat(p)
|
||||
if os.IsNotExist(err) || (err == nil && info.IsDir()) {
|
||||
miss = append(miss, name)
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
log.Printf("[batch_download] stat failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "internal error"})
|
||||
audit(c, "batch_download", gin.H{
|
||||
"file": name, "result": "stat_failed",
|
||||
})
|
||||
return
|
||||
}
|
||||
packed = append(packed, entry{path: p, size: info.Size()})
|
||||
}
|
||||
|
||||
if len(packed) == 0 {
|
||||
c.JSON(http.StatusNotFound, gin.H{
|
||||
"error": "no files available",
|
||||
"miss": miss,
|
||||
})
|
||||
audit(c, "batch_download", gin.H{
|
||||
"count": len(names), "packed": 0, "miss": miss,
|
||||
"result": "all_miss",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// 3. 流式 zip. WriteHeader 必须先于 body 写出, 之后 io.Copy 直写 c.Writer.
|
||||
zipName := "files-" + time.Now().Format("20060102-150405") + ".zip"
|
||||
c.Header("Content-Type", "application/zip")
|
||||
c.Header("Content-Disposition", `attachment; filename="`+zipName+`"`)
|
||||
c.Header("X-Content-Type-Options", "nosniff")
|
||||
c.Writer.WriteHeader(http.StatusOK)
|
||||
|
||||
zw := zip.NewWriter(c.Writer)
|
||||
now := time.Now()
|
||||
for _, e := range packed {
|
||||
fw, err := zw.Create(filepath.Base(e.path))
|
||||
if err != nil {
|
||||
log.Printf("[batch_download] zip create failed: %v", err)
|
||||
continue
|
||||
}
|
||||
f, err := os.Open(e.path)
|
||||
if err != nil {
|
||||
log.Printf("[batch_download] open failed: %v", err)
|
||||
continue
|
||||
}
|
||||
if _, err := io.Copy(fw, f); err != nil {
|
||||
log.Printf("[batch_download] copy failed: %v", err)
|
||||
}
|
||||
f.Close()
|
||||
_ = os.Chtimes(e.path, now, now) // 下载即续期, 与单文件一致
|
||||
}
|
||||
if err := zw.Close(); err != nil {
|
||||
log.Printf("[batch_download] zip close failed: %v", err)
|
||||
}
|
||||
|
||||
audit(c, "batch_download", gin.H{
|
||||
"count": len(names),
|
||||
"packed": len(packed),
|
||||
"miss": miss,
|
||||
"result": "ok",
|
||||
})
|
||||
}
|
||||
|
||||
@@ -50,6 +50,7 @@ func main() {
|
||||
// 业务路由
|
||||
r.POST("/upload", uploadHandler)
|
||||
r.GET("/download/:filename", downloadHandler)
|
||||
r.POST("/download-zip", batchDownloadHandler)
|
||||
r.DELETE("/files/:filename", deleteHandler)
|
||||
r.GET("/files", listHandler)
|
||||
|
||||
|
||||
@@ -270,6 +270,76 @@ else
|
||||
ko "gin mode" "not in release mode"
|
||||
fi
|
||||
|
||||
# ──────────────────────────────────────────────────────────────
|
||||
section "N. 批量下载 (POST /download-zip)"
|
||||
# ──────────────────────────────────────────────────────────────
|
||||
echo "batch-1" > "$TMPDIR/batch1.txt"
|
||||
echo "batch-2" > "$TMPDIR/batch2.txt"
|
||||
upload "$TMPDIR/batch1.txt" "batch1.txt" > /dev/null
|
||||
upload "$TMPDIR/batch2.txt" "batch2.txt" > /dev/null
|
||||
|
||||
zipfile="$TMPDIR/batch.zip"
|
||||
hdrs=$(curl -s -D - -o "$zipfile" -X POST -H "Content-Type: application/json" \
|
||||
-d '{"files":["batch1.txt","batch2.txt"]}' "$BASE/download-zip")
|
||||
status=$(echo "$hdrs" | tr -d '\r' | awk 'NR==1{print $2}')
|
||||
ctype=$(echo "$hdrs" | tr -d '\r' | awk -F': ' '/^[Cc]ontent-[Tt]ype/ {print $2}')
|
||||
if [[ "$status" == "200" ]] && echo "$ctype" | grep -qi 'application/zip'; then
|
||||
if unzip -l "$zipfile" 2>/dev/null | grep -qE 'batch1\.txt|batch2\.txt'; then
|
||||
ok "POST /download-zip -> 200 application/zip with both files"
|
||||
else
|
||||
ko "zip missing files" "unzip -l: $(unzip -l "$zipfile" 2>&1)"
|
||||
fi
|
||||
else
|
||||
ko "batch download baseline" "status=$status ctype=$ctype"
|
||||
fi
|
||||
|
||||
# 非法文件名: ".." 单独出现 -> 400; "../main.go" 清洗后变 "main.go" 不存在 -> 200+miss
|
||||
status=$(curl -s -o /dev/null -w "%{http_code}" -X POST -H "Content-Type: application/json" \
|
||||
-d '{"files":[".."]}' "$BASE/download-zip")
|
||||
[[ "$status" == "400" ]] && ok "\"..\" -> 400" || ko "explicit dotdot" "got $status"
|
||||
status=$(curl -s -o /dev/null -w "%{http_code}" -X POST -H "Content-Type: application/json" \
|
||||
-d '{"files":["."]}' "$BASE/download-zip")
|
||||
[[ "$status" == "400" ]] && ok "\".\" -> 400" || ko "explicit dot" "got $status"
|
||||
status=$(curl -s -o /dev/null -w "%{http_code}" -X POST -H "Content-Type: application/json" \
|
||||
-d '{"files":["../main.go"]}' "$BASE/download-zip")
|
||||
[[ "$status" == "200" || "$status" == "404" ]] && ok "../main.go sanitized, miss handled -> $status" || ko "sanitize+miss" "got $status"
|
||||
|
||||
# 不存在的文件: zip 仍生成, 含真实文件, 不含不存在的
|
||||
zipfile2="$TMPDIR/batch2.zip"
|
||||
status=$(curl -s -o "$zipfile2" -w "%{http_code}" -X POST -H "Content-Type: application/json" \
|
||||
-d '{"files":["batch1.txt","does-not-exist-12345.bin"]}' "$BASE/download-zip")
|
||||
if [[ "$status" == "200" ]]; then
|
||||
listing=$(unzip -l "$zipfile2" 2>/dev/null || true)
|
||||
if echo "$listing" | grep -q 'batch1.txt' && ! echo "$listing" | grep -q 'does-not-exist'; then
|
||||
ok "missing file skipped, real file still packed"
|
||||
else
|
||||
ko "missing file handling" "unzip -l: $listing"
|
||||
fi
|
||||
else
|
||||
ko "missing file request" "got $status"
|
||||
fi
|
||||
|
||||
# 超量
|
||||
files=$(python3 -c 'import json; print(json.dumps({"files":["x"]*101}))')
|
||||
status=$(curl -s -o /dev/null -w "%{http_code}" -X POST -H "Content-Type: application/json" \
|
||||
-d "$files" "$BASE/download-zip")
|
||||
[[ "$status" == "400" ]] && ok "101 files -> 400" || ko "101 files" "got $status"
|
||||
|
||||
# Query 形式
|
||||
status=$(curl -s -o "$TMPDIR/batch_q.zip" -w "%{http_code}" -X POST \
|
||||
"$BASE/download-zip?files=batch1.txt&files=batch2.txt")
|
||||
[[ "$status" == "200" ]] && ok "POST /download-zip?files=... -> 200" || ko "query form" "got $status"
|
||||
|
||||
# 空 files
|
||||
status=$(curl -s -o /dev/null -w "%{http_code}" -X POST -H "Content-Type: application/json" \
|
||||
-d '{"files":[]}' "$BASE/download-zip")
|
||||
[[ "$status" == "400" ]] && ok "empty files array -> 400" || ko "empty files" "got $status"
|
||||
|
||||
# 清理
|
||||
curl -s -X DELETE "$BASE/files/batch1.txt" > /dev/null
|
||||
curl -s -X DELETE "$BASE/files/batch2.txt" > /dev/null
|
||||
rm -f "$TMPDIR/batch.zip" "$TMPDIR/batch2.zip" "$TMPDIR/batch_q.zip"
|
||||
|
||||
# ──────────────────────────────────────────────────────────────
|
||||
echo
|
||||
printf "\n\033[1m========== 总计 ==========\033[0m\n"
|
||||
|
||||
@@ -176,6 +176,29 @@
|
||||
}
|
||||
.files-header h2 { font-size: 16px; font-weight: 600; }
|
||||
.files-header .meta { font-size: 12px; color: var(--text-dim); }
|
||||
.files-header-right {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
flex-wrap: wrap;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
.check-all-wrap {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 12px;
|
||||
color: var(--text-dim);
|
||||
cursor: pointer;
|
||||
user-select: none;
|
||||
}
|
||||
.check-all-wrap input {
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
accent-color: var(--primary);
|
||||
cursor: pointer;
|
||||
}
|
||||
.batch-btn { padding: 6px 14px; font-size: 13px; }
|
||||
|
||||
/* Quota */
|
||||
.quota-wrap { margin-bottom: 16px; }
|
||||
@@ -214,6 +237,13 @@
|
||||
border-radius: 8px;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
.file-check {
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
accent-color: var(--primary);
|
||||
cursor: pointer;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.file-icon {
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
|
||||
+19
-64
@@ -17,12 +17,18 @@ const quotaBar = $('quotaBar');
|
||||
const toastEl = $('toast');
|
||||
const totalProgress= $('totalProgress');
|
||||
const totalLabel = $('totalLabel');
|
||||
const checkAll = $('checkAll');
|
||||
const checkAllWrap = $('checkAllWrap');
|
||||
const batchBtn = $('batchBtn');
|
||||
const batchCount = $('batchCount');
|
||||
|
||||
// pending[i] = { id, file, xhr, status: 'pending'|'uploading'|'done'|'error'|'cancelled', progress, error }
|
||||
let pending = [];
|
||||
let nextId = 1;
|
||||
let isUploading = false;
|
||||
|
||||
// selectedFiles 在 batch.js 顶层 var 声明, 同 <script> 内共享.
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Toast
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -316,11 +322,19 @@ async function loadFiles() {
|
||||
quotaState = data.quota;
|
||||
if (!data.files || data.files.length === 0) {
|
||||
filesList.innerHTML = '<div class="empty">暂无文件</div>';
|
||||
selectedFiles.clear();
|
||||
updateBatchUI();
|
||||
return;
|
||||
}
|
||||
filesList.innerHTML = '';
|
||||
data.files.sort((a, b) => new Date(b.mod_time) - new Date(a.mod_time));
|
||||
// 清理已不存在文件的勾选 (跨刷新保留)
|
||||
const currentNames = new Set(data.files.map(f => f.filename));
|
||||
for (const n of [...selectedFiles]) {
|
||||
if (!currentNames.has(n)) selectedFiles.delete(n);
|
||||
}
|
||||
data.files.forEach(f => filesList.appendChild(fileRow(f)));
|
||||
updateBatchUI();
|
||||
} catch (e) {
|
||||
filesMeta.textContent = '加载失败';
|
||||
}
|
||||
@@ -348,7 +362,9 @@ function fileRow(f) {
|
||||
div.className = 'file-item';
|
||||
const ext = (f.filename.split('.').pop() || '').toLowerCase();
|
||||
const ttlHtml = `<span class="ttl" data-expires="${f.expires_at}">${formatRemain(f.expires_at)}</span>`;
|
||||
const checked = selectedFiles.has(f.filename) ? 'checked' : '';
|
||||
div.innerHTML = `
|
||||
<input type="checkbox" class="file-check" data-name="${escapeHtml(f.filename)}" ${checked} aria-label="选择 ${escapeHtml(f.filename)}" />
|
||||
<div class="file-icon">${iconFor(ext)}</div>
|
||||
<div class="file-info">
|
||||
<div class="file-name" title="${escapeHtml(f.filename)}">${escapeHtml(f.filename)}</div>
|
||||
@@ -364,6 +380,7 @@ function fileRow(f) {
|
||||
<button class="icon-btn danger" title="删除" data-delete="${escapeHtml(f.filename)}">✕</button>
|
||||
</div>
|
||||
`;
|
||||
div.querySelector('.file-check').addEventListener('change', e => onCheckChange(f.filename, e.target.checked));
|
||||
div.querySelector('[data-url]').onclick = () => copyToClipboard(location.origin + f.url);
|
||||
div.querySelector('[data-delete]').onclick = () => deleteFile(f.filename, div);
|
||||
return div;
|
||||
@@ -420,67 +437,5 @@ async function copyToClipboard(text) {
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 倒计时: 每秒刷新一次剩余时间
|
||||
// ---------------------------------------------------------------------------
|
||||
setInterval(() => {
|
||||
document.querySelectorAll('[data-expires]').forEach(el => {
|
||||
el.textContent = formatRemain(el.dataset.expires);
|
||||
el.classList.toggle('danger', isAlmostExpired(el.dataset.expires));
|
||||
});
|
||||
}, 1000);
|
||||
|
||||
function isAlmostExpired(iso) {
|
||||
const ms = new Date(iso).getTime() - Date.now();
|
||||
return ms > 0 && ms < 60 * 60 * 1000; // < 1h
|
||||
}
|
||||
|
||||
function formatRemain(iso) {
|
||||
const ms = new Date(iso).getTime() - Date.now();
|
||||
if (ms <= 0) return '已过期';
|
||||
const s = Math.floor(ms / 1000);
|
||||
if (s < 60) return `剩 ${s} 秒`;
|
||||
const m = Math.floor(s / 60);
|
||||
if (m < 60) return `剩 ${m} 分钟`;
|
||||
const h = Math.floor(m / 60);
|
||||
if (h < 24) return `剩 ${h} 小时${m % 60 ? ' ' + (m % 60) + ' 分' : ''}`;
|
||||
const d = Math.floor(h / 24);
|
||||
return `剩 ${d} 天${h % 24 ? ' ' + (h % 24) + ' 小时' : ''}`;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
function iconFor(ext) {
|
||||
const map = { pdf:'📄', zip:'📦', rar:'📦', '7z':'📦', txt:'📄', md:'📄',
|
||||
png:'🖼', jpg:'🖼', jpeg:'🖼', gif:'🖼', webp:'🖼', svg:'🖼',
|
||||
mp4:'🎬', mov:'🎬', avi:'🎬', mkv:'🎬',
|
||||
mp3:'🎵', wav:'🎵', flac:'🎵',
|
||||
xls:'📊', xlsx:'📊', csv:'📊',
|
||||
doc:'📃', docx:'📃', ppt:'📽', pptx:'📽' };
|
||||
return map[ext] || '📁';
|
||||
}
|
||||
|
||||
function formatSize(b) {
|
||||
if (b == null || isNaN(b)) return '-';
|
||||
if (b < 1024) return b + ' B';
|
||||
if (b < 1024 * 1024) return (b / 1024).toFixed(1) + ' KB';
|
||||
if (b < 1024 * 1024 * 1024) return (b / 1024 / 1024).toFixed(2) + ' MB';
|
||||
return (b / 1024 / 1024 / 1024).toFixed(2) + ' GB';
|
||||
}
|
||||
|
||||
function formatTime(iso) {
|
||||
const d = new Date(iso);
|
||||
const pad = n => String(n).padStart(2, '0');
|
||||
return `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
|
||||
}
|
||||
|
||||
function escapeHtml(s) {
|
||||
return String(s).replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Boot
|
||||
// ---------------------------------------------------------------------------
|
||||
loadFiles();
|
||||
setInterval(loadFiles, 30000);
|
||||
// formatRemain / isAlmostExpired / iconFor / formatSize / formatTime / escapeHtml
|
||||
// 见 helpers.js; 倒计时 setInterval 也在 helpers.js 中启动
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
'use strict';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 批量选择 / 批量下载 (依赖 app.js 的 consts: checkAll, checkAllWrap,
|
||||
// batchBtn, batchCount, filesList, toast)
|
||||
// 用 var 顶层声明, 与 app.js 同 <script> 内共享 (loadFiles / fileRow 读写).
|
||||
// ---------------------------------------------------------------------------
|
||||
var selectedFiles = new Set();
|
||||
|
||||
function onCheckChange(name, checked) {
|
||||
if (checked) selectedFiles.add(name);
|
||||
else selectedFiles.delete(name);
|
||||
updateBatchUI();
|
||||
}
|
||||
|
||||
function updateBatchUI() {
|
||||
const n = selectedFiles.size;
|
||||
batchCount.textContent = n;
|
||||
batchBtn.style.display = n > 0 ? 'inline-block' : 'none';
|
||||
|
||||
const checks = filesList.querySelectorAll('.file-check');
|
||||
if (checks.length === 0) {
|
||||
checkAllWrap.style.display = 'none';
|
||||
checkAll.checked = false;
|
||||
checkAll.indeterminate = false;
|
||||
return;
|
||||
}
|
||||
checkAllWrap.style.display = 'inline-flex';
|
||||
let checkedCount = 0;
|
||||
checks.forEach(c => { if (c.checked) checkedCount++; });
|
||||
checkAll.checked = checkedCount === checks.length;
|
||||
checkAll.indeterminate = checkedCount > 0 && checkedCount < checks.length;
|
||||
}
|
||||
|
||||
checkAll.addEventListener('change', () => {
|
||||
const want = checkAll.checked;
|
||||
filesList.querySelectorAll('.file-check').forEach(c => {
|
||||
if (c.checked !== want) {
|
||||
c.checked = want;
|
||||
const name = c.dataset.name;
|
||||
if (want) selectedFiles.add(name);
|
||||
else selectedFiles.delete(name);
|
||||
}
|
||||
});
|
||||
updateBatchUI();
|
||||
});
|
||||
|
||||
batchBtn.addEventListener('click', async () => {
|
||||
if (selectedFiles.size === 0) return;
|
||||
const names = [...selectedFiles];
|
||||
batchBtn.disabled = true;
|
||||
const restore = () => { batchBtn.disabled = false; batchBtn.textContent = `批量下载 (${selectedFiles.size})`; };
|
||||
batchBtn.textContent = '打包中...';
|
||||
try {
|
||||
const r = await fetch('/download-zip', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ files: names }),
|
||||
});
|
||||
if (!r.ok) {
|
||||
let msg = 'HTTP ' + r.status;
|
||||
try { msg = (await r.json()).error || msg; } catch {}
|
||||
throw new Error(msg);
|
||||
}
|
||||
// 从 Content-Disposition 取 server 起的 zip 文件名, 兜底 'files.zip'
|
||||
let fname = 'files.zip';
|
||||
const cd = r.headers.get('Content-Disposition') || '';
|
||||
const m = cd.match(/filename="?([^";]+)"?/);
|
||||
if (m) fname = m[1];
|
||||
const blob = await r.blob();
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url; a.download = fname;
|
||||
document.body.appendChild(a); a.click(); document.body.removeChild(a);
|
||||
setTimeout(() => URL.revokeObjectURL(url), 1000);
|
||||
toast(`已下载 ${names.length} 个文件`, 'success');
|
||||
} catch (e) {
|
||||
toast('批量下载失败: ' + e.message, 'error');
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Boot (从 app.js 末尾移过来, 确保 selectedFiles 已声明再启动首次 loadFiles)
|
||||
// ---------------------------------------------------------------------------
|
||||
loadFiles();
|
||||
setInterval(loadFiles, 30000);
|
||||
@@ -0,0 +1,59 @@
|
||||
'use strict';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 纯函数 + 倒计时 interval
|
||||
// 与 app.js 同 <script> 内共享 (load order: app → helpers → batch).
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function formatRemain(iso) {
|
||||
const ms = new Date(iso).getTime() - Date.now();
|
||||
if (ms <= 0) return '已过期';
|
||||
const s = Math.floor(ms / 1000);
|
||||
if (s < 60) return `剩 ${s} 秒`;
|
||||
const m = Math.floor(s / 60);
|
||||
if (m < 60) return `剩 ${m} 分钟`;
|
||||
const h = Math.floor(m / 60);
|
||||
if (h < 24) return `剩 ${h} 小时${m % 60 ? ' ' + (m % 60) + ' 分' : ''}`;
|
||||
const d = Math.floor(h / 24);
|
||||
return `剩 ${d} 天${h % 24 ? ' ' + (h % 24) + ' 小时' : ''}`;
|
||||
}
|
||||
|
||||
function isAlmostExpired(iso) {
|
||||
const ms = new Date(iso).getTime() - Date.now();
|
||||
return ms > 0 && ms < 60 * 60 * 1000; // < 1h
|
||||
}
|
||||
|
||||
setInterval(() => {
|
||||
document.querySelectorAll('[data-expires]').forEach(el => {
|
||||
el.textContent = formatRemain(el.dataset.expires);
|
||||
el.classList.toggle('danger', isAlmostExpired(el.dataset.expires));
|
||||
});
|
||||
}, 1000);
|
||||
|
||||
function iconFor(ext) {
|
||||
const map = { pdf:'📄', zip:'📦', rar:'📦', '7z':'📦', txt:'📄', md:'📄',
|
||||
png:'🖼', jpg:'🖼', jpeg:'🖼', gif:'🖼', webp:'🖼', svg:'🖼',
|
||||
mp4:'🎬', mov:'🎬', avi:'🎬', mkv:'🎬',
|
||||
mp3:'🎵', wav:'🎵', flac:'🎵',
|
||||
xls:'📊', xlsx:'📊', csv:'📊',
|
||||
doc:'📃', docx:'📃', ppt:'📽', pptx:'📽' };
|
||||
return map[ext] || '📁';
|
||||
}
|
||||
|
||||
function formatSize(b) {
|
||||
if (b == null || isNaN(b)) return '-';
|
||||
if (b < 1024) return b + ' B';
|
||||
if (b < 1024 * 1024) return (b / 1024).toFixed(1) + ' KB';
|
||||
if (b < 1024 * 1024 * 1024) return (b / 1024 / 1024).toFixed(2) + ' MB';
|
||||
return (b / 1024 / 1024 / 1024).toFixed(2) + ' GB';
|
||||
}
|
||||
|
||||
function formatTime(iso) {
|
||||
const d = new Date(iso);
|
||||
const pad = n => String(n).padStart(2, '0');
|
||||
return `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
|
||||
}
|
||||
|
||||
function escapeHtml(s) {
|
||||
return String(s).replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
|
||||
}
|
||||
@@ -35,7 +35,14 @@
|
||||
<div class="card">
|
||||
<div class="files-header">
|
||||
<h2>文件列表</h2>
|
||||
<span class="meta" id="filesMeta">加载中...</span>
|
||||
<div class="files-header-right">
|
||||
<label class="check-all-wrap" id="checkAllWrap" style="display:none">
|
||||
<input type="checkbox" id="checkAll" />
|
||||
<span>全选</span>
|
||||
</label>
|
||||
<span class="meta" id="filesMeta">加载中...</span>
|
||||
<button class="btn ghost batch-btn" id="batchBtn" style="display:none">批量下载 (<span id="batchCount">0</span>)</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="quota-wrap" id="quotaWrap" style="display:none">
|
||||
<div class="quota-row">
|
||||
|
||||
Reference in New Issue
Block a user