feat: batch delete
This commit is contained in:
@@ -48,11 +48,12 @@ curl -F "file=@report.pdf" http://localhost:8080/upload
|
|||||||
|
|
||||||
| Method | Path | 说明 |
|
| Method | Path | 说明 |
|
||||||
|--------|----------------------------|--------------------------------------------|
|
|--------|----------------------------|--------------------------------------------|
|
||||||
| GET | `/` | Web UI(单 HTML 响应,内联 CSS + JS) |
|
| GET | `/` | Web UI(单 HTML 响应,CSS/JS 经 `/static` 引用) |
|
||||||
| POST | `/upload` | 上传文件(`multipart/form-data`,字段名 `file`) |
|
| POST | `/upload` | 上传文件(`multipart/form-data`,字段名 `file`) |
|
||||||
| GET | `/files` | 列出当前未过期文件 |
|
| GET | `/files` | 列出当前未过期文件 |
|
||||||
| GET | `/download/:filename` | 下载文件 |
|
| GET | `/download/:filename` | 下载文件 |
|
||||||
| POST | `/download-zip` | 批量下载 (body: `{"files":[...]}`, 最多 100 项) |
|
| POST | `/download-zip` | 批量下载 (body: `{"files":[...]}`, 最多 100 项) |
|
||||||
|
| POST | `/files-delete` | 批量删除 (body: `{"files":[...]}`, 最多 100 项) |
|
||||||
| DELETE | `/files/:filename` | 删除文件 |
|
| DELETE | `/files/:filename` | 删除文件 |
|
||||||
|
|
||||||
---
|
---
|
||||||
@@ -61,29 +62,31 @@ curl -F "file=@report.pdf" http://localhost:8080/upload
|
|||||||
|
|
||||||
```text
|
```text
|
||||||
tmp-upload/
|
tmp-upload/
|
||||||
├── main.go # 入口、配置、路由注册 (61 行)
|
├── main.go # 入口、配置、路由注册 (72 行)
|
||||||
├── embed.go # //go:embed + init() 拼接 (38 行)
|
├── embed.go # //go:embed + fs.Sub 静态资源 (26 行)
|
||||||
├── audit.go # 审计日志子系统 (102 行)
|
├── audit.go # 审计日志子系统 (102 行)
|
||||||
├── quota.go # 配额管理 + formatSize (112 行)
|
├── quota.go # 配额管理 + formatSize (112 行)
|
||||||
├── handlers.go # HTTP handlers + DTOs (440 行)
|
├── handlers.go # HTTP handlers + DTOs (308 行)
|
||||||
|
├── batch.go # 批量下载 / 批量删除 handlers (248 行)
|
||||||
├── cleaner.go # TTL 过期清理 (57 行)
|
├── cleaner.go # TTL 过期清理 (57 行)
|
||||||
├── audit_test.go # audit 单元测试
|
├── audit_test.go # audit 单元测试
|
||||||
├── security_test.sh # HTTP 端到端测试
|
├── security_test.sh # HTTP 端到端测试
|
||||||
├── go.mod / go.sum
|
├── go.mod / go.sum
|
||||||
└── static/
|
└── static/
|
||||||
├── index.html.tpl # HTML 骨架 (含 /*EMBED_CSS*/、/*EMBED_JS*/ 占位符)
|
├── index.html.tpl # HTML 骨架 (经 /static 引用 CSS/JS, 含批量删除按钮)
|
||||||
├── app.css # CSS (357 行)
|
├── app.css # CSS (359 行)
|
||||||
├── app.js # JS — 主程序 (441 行)
|
├── app.js # JS — 主程序 (443 行)
|
||||||
├── helpers.js # JS — 纯函数 + 倒计时 (58 行)
|
├── helpers.js # JS — 纯函数 + 倒计时 (58 行)
|
||||||
└── batch.js # JS — 批量选择 / 批量下载 (87 行)
|
└── batch.js # JS — 批量选择 / 批量下载 / 批量删除 (119 行)
|
||||||
```
|
```
|
||||||
|
|
||||||
### 单文件部署说明
|
### 单文件部署说明
|
||||||
|
|
||||||
`embed.go` 用 `//go:embed` 把三个静态文件全部编入二进制,
|
`embed.go` 用 `//go:embed` 把 `static/` 下的 CSS/JS 编入二进制,
|
||||||
在 `init()` 中用 `strings.Replace` 把 CSS/JS 拼到 HTML 骨架里生成 `pageHTML`。
|
在 `init()` 中用 `fs.Sub` 切出 `static/` 子文件系统供 `/static` 路由对外提供;
|
||||||
浏览器访问 `/` 拿到的是**一个**完整 HTML 响应(HTML+CSS+JS 全部内联),
|
HTML 骨架 `index.html.tpl` 单独 embed,`GET /` 直接返回。
|
||||||
不产生额外的 `<link>` / `<script src=>` 请求。
|
浏览器加载的是拆分请求(HTML + `<link>` CSS + `<script>` JS),
|
||||||
|
但所有资源仍编译进单个二进制,部署依旧单文件,无需运行时外部文件。
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,255 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"archive/zip"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
// 批量下载: 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",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
// 批量删除: POST /files-delete (body: {"files":[...]})
|
||||||
|
// 破坏性操作, 仅接受 JSON body, 不做 query fallback (不接受 URL 参数驱动).
|
||||||
|
// 两阶段: 先全量 stat (缺失/目录 → miss), 再逐个 os.Remove, 失败继续并计入 failed.
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
func batchDeleteHandler(c *gin.Context) {
|
||||||
|
// 1. 仅接受 JSON body 收集 filenames, 不做 query fallback (破坏性操作)
|
||||||
|
var req batchRequest
|
||||||
|
jsonBody := c.Request.ContentLength > 0 &&
|
||||||
|
strings.HasPrefix(c.GetHeader("Content-Type"), "application/json")
|
||||||
|
if !jsonBody {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "no files specified"})
|
||||||
|
audit(c, "batch_delete", gin.H{"result": "no_files"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := c.ShouldBindJSON(&req); err != nil || len(req.Files) == 0 {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "no files specified"})
|
||||||
|
audit(c, "batch_delete", gin.H{"result": "no_files"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
names := req.Files
|
||||||
|
if len(names) > batchMaxFiles {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{
|
||||||
|
"error": fmt.Sprintf("too many files (max %d)", batchMaxFiles),
|
||||||
|
})
|
||||||
|
audit(c, "batch_delete", gin.H{
|
||||||
|
"count": len(names), "result": "too_many",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. 校验每个文件名, 第一遍 stat (缺失/目录 → miss; 其他错误 → 500)
|
||||||
|
type entry struct {
|
||||||
|
path string
|
||||||
|
size int64
|
||||||
|
}
|
||||||
|
var targets []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_delete", 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_delete", 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_delete] stat failed: %v", err)
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "internal error"})
|
||||||
|
audit(c, "batch_delete", gin.H{
|
||||||
|
"file": name, "result": "stat_failed",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
targets = append(targets, entry{path: p, size: info.Size()})
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. 逐个 os.Remove; 失败 log + 计入 failed 并继续; 成功扣配额
|
||||||
|
failed := []string{} // 非 nil, JSON 输出 [] 而非 null
|
||||||
|
deleted := 0
|
||||||
|
for _, t := range targets {
|
||||||
|
if err := os.Remove(t.path); err != nil {
|
||||||
|
log.Printf("[batch_delete] remove failed: %v", err)
|
||||||
|
failed = append(failed, filepath.Base(t.path))
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
quotaSub(t.size)
|
||||||
|
deleted++
|
||||||
|
}
|
||||||
|
|
||||||
|
if deleted == 0 {
|
||||||
|
c.JSON(http.StatusNotFound, gin.H{
|
||||||
|
"error": "no files deleted",
|
||||||
|
"miss": miss,
|
||||||
|
"failed": failed,
|
||||||
|
})
|
||||||
|
audit(c, "batch_delete", gin.H{
|
||||||
|
"count": len(names), "deleted": deleted, "miss": miss, "failed": failed,
|
||||||
|
"result": "all_miss",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"deleted": deleted,
|
||||||
|
"miss": miss,
|
||||||
|
"failed": failed,
|
||||||
|
})
|
||||||
|
audit(c, "batch_delete", gin.H{
|
||||||
|
"count": len(names), "deleted": deleted, "miss": miss, "failed": failed,
|
||||||
|
"result": "ok",
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -1,38 +1,26 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"strings"
|
"embed"
|
||||||
|
"io/fs"
|
||||||
_ "embed"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// 嵌入式静态页面 (单文件部署, 把 HTML/CSS/JS 编译进二进制, 无需运行时外部文件)
|
// 嵌入式静态资源: HTML 骨架单独 embed, CSS/JS 经 /static 路由对外提供.
|
||||||
|
// 所有资源仍编译进单个二进制, 部署无需运行时外部文件.
|
||||||
|
|
||||||
|
//go:embed static/app.css static/app.js static/helpers.js static/batch.js
|
||||||
|
var staticEmbed embed.FS
|
||||||
|
|
||||||
//go:embed static/index.html.tpl
|
//go:embed static/index.html.tpl
|
||||||
var indexTpl []byte
|
var indexTpl []byte
|
||||||
|
|
||||||
//go:embed static/app.css
|
// staticFS 是 static/ 目录的子文件系统, 供 /static 路由对外提供资源.
|
||||||
var appCSS []byte
|
var staticFS fs.FS
|
||||||
|
|
||||||
//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
|
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
s := string(indexTpl)
|
var err error
|
||||||
s = strings.Replace(s, "/*EMBED_CSS*/", string(appCSS), 1)
|
staticFS, err = fs.Sub(staticEmbed, "static")
|
||||||
// JS 顺序敏感: app 先声明 consts / 注册 handlers; helpers 后注入纯函数;
|
if err != nil {
|
||||||
// batch 最后使用 consts 并启动 boot. 同 <script> 内共享顶层 var.
|
panic(err)
|
||||||
combined := string(appJS) + "\n" + string(helpersJS) + "\n" + string(batchJS)
|
}
|
||||||
s = strings.Replace(s, "/*EMBED_JS*/", combined, 1)
|
|
||||||
pageHTML = []byte(s)
|
|
||||||
}
|
}
|
||||||
|
|||||||
-133
@@ -1,9 +1,7 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"archive/zip"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
|
||||||
"log"
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
@@ -307,134 +305,3 @@ func deleteHandler(c *gin.Context) {
|
|||||||
c.JSON(http.StatusOK, gin.H{"deleted": name})
|
c.JSON(http.StatusOK, gin.H{"deleted": name})
|
||||||
audit(c, "delete", gin.H{"file": name, "size": info.Size(), "result": "ok"})
|
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",
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import (
|
|||||||
"flag"
|
"flag"
|
||||||
"log"
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
@@ -38,19 +39,28 @@ func main() {
|
|||||||
}
|
}
|
||||||
initQuota()
|
initQuota()
|
||||||
|
|
||||||
gin.SetMode(gin.ReleaseMode)
|
|
||||||
r := gin.New()
|
r := gin.New()
|
||||||
r.Use(gin.Logger(), gin.Recovery(), auditT0())
|
r.Use(gin.Logger(), gin.Recovery(), auditT0())
|
||||||
|
|
||||||
// 嵌入式首页
|
// 嵌入式首页 (HTML 骨架, CSS/JS 经 /static 引用)
|
||||||
r.GET("/", func(c *gin.Context) {
|
r.GET("/", func(c *gin.Context) {
|
||||||
c.Data(http.StatusOK, "text/html; charset=utf-8", pageHTML)
|
c.Data(http.StatusOK, "text/html; charset=utf-8", indexTpl)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// 静态资源 (CSS/JS): no-cache 防止二进制升级后浏览器使用旧缓存 JS
|
||||||
|
r.Use(func(c *gin.Context) {
|
||||||
|
if strings.HasPrefix(c.Request.URL.Path, "/static") {
|
||||||
|
c.Header("Cache-Control", "no-cache")
|
||||||
|
}
|
||||||
|
c.Next()
|
||||||
|
})
|
||||||
|
r.StaticFS("/static", http.FS(staticFS))
|
||||||
|
|
||||||
// 业务路由
|
// 业务路由
|
||||||
r.POST("/upload", uploadHandler)
|
r.POST("/upload", uploadHandler)
|
||||||
r.GET("/download/:filename", downloadHandler)
|
r.GET("/download/:filename", downloadHandler)
|
||||||
r.POST("/download-zip", batchDownloadHandler)
|
r.POST("/download-zip", batchDownloadHandler)
|
||||||
|
r.POST("/files-delete", batchDeleteHandler)
|
||||||
r.DELETE("/files/:filename", deleteHandler)
|
r.DELETE("/files/:filename", deleteHandler)
|
||||||
r.GET("/files", listHandler)
|
r.GET("/files", listHandler)
|
||||||
|
|
||||||
|
|||||||
@@ -340,6 +340,71 @@ curl -s -X DELETE "$BASE/files/batch1.txt" > /dev/null
|
|||||||
curl -s -X DELETE "$BASE/files/batch2.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"
|
rm -f "$TMPDIR/batch.zip" "$TMPDIR/batch2.zip" "$TMPDIR/batch_q.zip"
|
||||||
|
|
||||||
|
# ──────────────────────────────────────────────────────────────
|
||||||
|
section "O. 批量删除 (POST /files-delete)"
|
||||||
|
# ──────────────────────────────────────────────────────────────
|
||||||
|
echo "bdel-1" > "$TMPDIR/bdel1.txt"
|
||||||
|
echo "bdel-2" > "$TMPDIR/bdel2.txt"
|
||||||
|
upload "$TMPDIR/bdel1.txt" "bdel1.txt" > /dev/null
|
||||||
|
upload "$TMPDIR/bdel2.txt" "bdel2.txt" > /dev/null
|
||||||
|
|
||||||
|
# 删除其一 + 一个不存在: 200, miss 含不存在项, 目标文件确已被删
|
||||||
|
resp=$(curl -s -X POST -H "Content-Type: application/json" \
|
||||||
|
-d '{"files":["bdel1.txt","does-not-exist-bdel.bin"]}' "$BASE/files-delete")
|
||||||
|
if echo "$resp" | grep -q '"deleted":1' && echo "$resp" | grep -q 'does-not-exist-bdel.bin'; then
|
||||||
|
ok "POST /files-delete (1 real + 1 miss) -> 200 deleted=1 miss=[...]"
|
||||||
|
else
|
||||||
|
ko "batch delete baseline" "resp=$resp"
|
||||||
|
fi
|
||||||
|
status=$(curl -s -o /dev/null -w "%{http_code}" "$BASE/download/bdel1.txt")
|
||||||
|
[[ "$status" == "404" ]] && ok "deleted file no longer downloadable -> 404" || ko "deleted file" "got $status"
|
||||||
|
|
||||||
|
# 非法文件名 -> 400
|
||||||
|
status=$(curl -s -o /dev/null -w "%{http_code}" -X POST -H "Content-Type: application/json" \
|
||||||
|
-d '{"files":[".."]}' "$BASE/files-delete")
|
||||||
|
[[ "$status" == "400" ]] && ok "invalid filename \"..\" -> 400" || ko "invalid filename" "got $status"
|
||||||
|
|
||||||
|
# 超 100 -> 400
|
||||||
|
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/files-delete")
|
||||||
|
[[ "$status" == "400" ]] && ok "101 files -> 400" || ko "101 files" "got $status"
|
||||||
|
|
||||||
|
# 空 body -> 400
|
||||||
|
status=$(curl -s -o /dev/null -w "%{http_code}" -X POST -H "Content-Type: application/json" \
|
||||||
|
-d '{"files":[]}' "$BASE/files-delete")
|
||||||
|
[[ "$status" == "400" ]] && ok "empty files array -> 400" || ko "empty files" "got $status"
|
||||||
|
|
||||||
|
# 清理
|
||||||
|
curl -s -X DELETE "$BASE/files/bdel2.txt" > /dev/null
|
||||||
|
|
||||||
|
# ──────────────────────────────────────────────────────────────
|
||||||
|
section "P. 静态资源 (/static StaticFS)"
|
||||||
|
# ──────────────────────────────────────────────────────────────
|
||||||
|
html=$(curl -s "$BASE/")
|
||||||
|
if echo "$html" | grep -q 'href="/static/app.css"'; then
|
||||||
|
ok "GET / contains <link href=\"/static/app.css\">"
|
||||||
|
else
|
||||||
|
ko "GET / link tag" "link tag missing"
|
||||||
|
fi
|
||||||
|
for js in app.js helpers.js batch.js; do
|
||||||
|
code=$(status "$BASE/static/$js")
|
||||||
|
[[ "$code" == "200" ]] && ok "GET /static/$js -> 200" || ko "GET /static/$js" "got $code"
|
||||||
|
done
|
||||||
|
hdrs=$(curl -s -D - -o /dev/null "$BASE/static/app.css")
|
||||||
|
ctype=$(echo "$hdrs" | tr -d '\r' | awk -F': ' '/^[Cc]ontent-[Tt]ype/ {print $2}')
|
||||||
|
cc=$(echo "$hdrs" | tr -d '\r' | awk -F': ' '/^[Cc]ache-[Cc]ontrol/ {print $2}')
|
||||||
|
if echo "$ctype" | grep -qi 'text/css'; then
|
||||||
|
ok "GET /static/app.css -> Content-Type: text/css"
|
||||||
|
else
|
||||||
|
ko "app.css content-type" "got [$ctype]"
|
||||||
|
fi
|
||||||
|
if echo "$cc" | grep -qi 'no-cache'; then
|
||||||
|
ok "GET /static/app.css -> Cache-Control: no-cache"
|
||||||
|
else
|
||||||
|
ko "app.css cache-control" "got [$cc]"
|
||||||
|
fi
|
||||||
|
|
||||||
# ──────────────────────────────────────────────────────────────
|
# ──────────────────────────────────────────────────────────────
|
||||||
echo
|
echo
|
||||||
printf "\n\033[1m========== 总计 ==========\033[0m\n"
|
printf "\n\033[1m========== 总计 ==========\033[0m\n"
|
||||||
|
|||||||
@@ -92,6 +92,8 @@
|
|||||||
.btn:disabled { background: var(--text-dim); cursor: not-allowed; }
|
.btn:disabled { background: var(--text-dim); cursor: not-allowed; }
|
||||||
.btn.ghost { background: var(--panel-2); }
|
.btn.ghost { background: var(--panel-2); }
|
||||||
.btn.danger { background: var(--danger); }
|
.btn.danger { background: var(--danger); }
|
||||||
|
.btn.ghost.danger { background: var(--panel-2); color: var(--danger); border: 1px solid var(--danger); }
|
||||||
|
.btn.ghost.danger:hover { background: var(--danger); color: #0f1115; }
|
||||||
.btn-row { display: flex; gap: 12px; margin-top: 16px; flex-wrap: wrap; align-items: center; }
|
.btn-row { display: flex; gap: 12px; margin-top: 16px; flex-wrap: wrap; align-items: center; }
|
||||||
|
|
||||||
/* Progress */
|
/* Progress */
|
||||||
|
|||||||
+3
-1
@@ -21,13 +21,15 @@ const checkAll = $('checkAll');
|
|||||||
const checkAllWrap = $('checkAllWrap');
|
const checkAllWrap = $('checkAllWrap');
|
||||||
const batchBtn = $('batchBtn');
|
const batchBtn = $('batchBtn');
|
||||||
const batchCount = $('batchCount');
|
const batchCount = $('batchCount');
|
||||||
|
const batchDeleteBtn = $('batchDeleteBtn');
|
||||||
|
const batchDeleteCount= $('batchDeleteCount');
|
||||||
|
|
||||||
// pending[i] = { id, file, xhr, status: 'pending'|'uploading'|'done'|'error'|'cancelled', progress, error }
|
// pending[i] = { id, file, xhr, status: 'pending'|'uploading'|'done'|'error'|'cancelled', progress, error }
|
||||||
let pending = [];
|
let pending = [];
|
||||||
let nextId = 1;
|
let nextId = 1;
|
||||||
let isUploading = false;
|
let isUploading = false;
|
||||||
|
|
||||||
// selectedFiles 在 batch.js 顶层 var 声明, 同 <script> 内共享.
|
// selectedFiles 在 batch.js 顶层 var 声明, 跨文件共享 (classic <script> 加载顺序: app.js → helpers.js → batch.js).
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
// Toast
|
// Toast
|
||||||
|
|||||||
+35
-4
@@ -1,9 +1,9 @@
|
|||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
// 批量选择 / 批量下载 (依赖 app.js 的 consts: checkAll, checkAllWrap,
|
// 批量选择 / 批量下载 / 批量删除 (依赖 app.js 的 consts: checkAll, checkAllWrap,
|
||||||
// batchBtn, batchCount, filesList, toast)
|
// batchBtn, batchCount, batchDeleteBtn, batchDeleteCount, filesList, toast)
|
||||||
// 用 var 顶层声明, 与 app.js 同 <script> 内共享 (loadFiles / fileRow 读写).
|
// 用 var 顶层声明, 跨文件共享 (classic <script> 加载顺序: app.js → helpers.js → batch.js).
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
var selectedFiles = new Set();
|
var selectedFiles = new Set();
|
||||||
|
|
||||||
@@ -17,6 +17,8 @@ function updateBatchUI() {
|
|||||||
const n = selectedFiles.size;
|
const n = selectedFiles.size;
|
||||||
batchCount.textContent = n;
|
batchCount.textContent = n;
|
||||||
batchBtn.style.display = n > 0 ? 'inline-block' : 'none';
|
batchBtn.style.display = n > 0 ? 'inline-block' : 'none';
|
||||||
|
batchDeleteCount.textContent = n;
|
||||||
|
batchDeleteBtn.style.display = n > 0 ? 'inline-block' : 'none';
|
||||||
|
|
||||||
const checks = filesList.querySelectorAll('.file-check');
|
const checks = filesList.querySelectorAll('.file-check');
|
||||||
if (checks.length === 0) {
|
if (checks.length === 0) {
|
||||||
@@ -81,8 +83,37 @@ batchBtn.addEventListener('click', async () => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
batchDeleteBtn.addEventListener('click', async () => {
|
||||||
|
if (selectedFiles.size === 0) return;
|
||||||
|
const names = [...selectedFiles];
|
||||||
|
if (!confirm(`确定删除选中的 ${names.length} 个文件吗? 该操作不可恢复.`)) return;
|
||||||
|
batchDeleteBtn.disabled = true;
|
||||||
|
const restore = () => { batchDeleteBtn.disabled = false; batchDeleteBtn.textContent = `批量删除 (${selectedFiles.size})`; };
|
||||||
|
batchDeleteBtn.textContent = '删除中...';
|
||||||
|
try {
|
||||||
|
const r = await fetch('/files-delete', {
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
const data = await r.json();
|
||||||
|
toast(`已删除 ${data.deleted} 个文件`, 'success');
|
||||||
|
selectedFiles.clear();
|
||||||
|
await loadFiles();
|
||||||
|
} catch (e) {
|
||||||
|
toast('批量删除失败: ' + e.message, 'error');
|
||||||
|
} finally {
|
||||||
|
restore();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
// Boot (从 app.js 末尾移过来, 确保 selectedFiles 已声明再启动首次 loadFiles)
|
// Boot (从 app.js 末尾移过来, 确保 selectedFiles 已声明再启动首次 loadFiles)
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
loadFiles();
|
loadFiles();
|
||||||
setInterval(loadFiles, 30000);
|
setInterval(loadFiles, 30000);
|
||||||
|
|||||||
+1
-1
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
// 纯函数 + 倒计时 interval
|
// 纯函数 + 倒计时 interval
|
||||||
// 与 app.js 同 <script> 内共享 (load order: app → helpers → batch).
|
// 跨文件共享 (classic <script> 加载顺序: app.js → helpers.js → batch.js).
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
function formatRemain(iso) {
|
function formatRemain(iso) {
|
||||||
|
|||||||
@@ -4,8 +4,7 @@
|
|||||||
<meta charset="UTF-8" />
|
<meta charset="UTF-8" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
<title>临时文件上传 · TTL 24h</title>
|
<title>临时文件上传 · TTL 24h</title>
|
||||||
<style>
|
<link rel="stylesheet" href="/static/app.css" />
|
||||||
/*EMBED_CSS*/</style>
|
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div class="container">
|
<div class="container">
|
||||||
@@ -42,6 +41,7 @@
|
|||||||
</label>
|
</label>
|
||||||
<span class="meta" id="filesMeta">加载中...</span>
|
<span class="meta" id="filesMeta">加载中...</span>
|
||||||
<button class="btn ghost batch-btn" id="batchBtn" style="display:none">批量下载 (<span id="batchCount">0</span>)</button>
|
<button class="btn ghost batch-btn" id="batchBtn" style="display:none">批量下载 (<span id="batchCount">0</span>)</button>
|
||||||
|
<button class="btn ghost batch-btn danger" id="batchDeleteBtn" style="display:none">批量删除 (<span id="batchDeleteCount">0</span>)</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="quota-wrap" id="quotaWrap" style="display:none">
|
<div class="quota-wrap" id="quotaWrap" style="display:none">
|
||||||
@@ -62,7 +62,8 @@
|
|||||||
|
|
||||||
<div class="toast" id="toast"></div>
|
<div class="toast" id="toast"></div>
|
||||||
|
|
||||||
<script>
|
<script src="/static/app.js"></script>
|
||||||
/*EMBED_JS*/</script>
|
<script src="/static/helpers.js"></script>
|
||||||
|
<script src="/static/batch.js"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
Reference in New Issue
Block a user