This commit is contained in:
tao.chen
2026-08-27 12:58:48 +08:00
parent c8e4996c34
commit 7225b72906
10 changed files with 1092 additions and 923 deletions
+107
View File
@@ -0,0 +1,107 @@
# tmp-upload
一个自托管的临时文件分享服务。上传文件后获得一个下载链接,**24 小时后自动删除**。
* Single binary,no runtime dependencies
* Built-in web UI (zero external assets)
* 10 GB default quota (configurable)
* Daily audit log (optional)
---
## 快速开始
```bash
go build -o server .
./server
# → 浏览器打开 http://localhost:8080
```
```bash
# 命令行上传
curl -F "file=@report.pdf" http://localhost:8080/upload
# → {"filename":"report.pdf","url":"/download/report-2026-08-27-abc123.pdf","expires_at":"..."}
```
---
## 配置(命令行 flag)
```text
-dir ./data/uploads 上传文件保存目录
-listen :8080 HTTP 监听地址
-ttl 24h 文件过期 TTL
-scan 1h 清理扫描间隔
-quota 10737418240 总目录配额(字节,默认 10 GB;0 = 不限)
-audit-dir ./data/audit 审计日志目录(每天一个 YYYY-MM-DD.log 文件;空字符串禁用)
```
示例:把 TTL 改成 1 小时、配额 1 GB:
```bash
./server -ttl 1h -quota 1073741824
```
---
## HTTP API
| Method | Path | 说明 |
|--------|----------------------------|--------------------------------------------|
| GET | `/` | Web UI(单 HTML 响应,内联 CSS + JS) |
| POST | `/upload` | 上传文件(`multipart/form-data`,字段名 `file`) |
| GET | `/files` | 列出当前未过期文件 |
| GET | `/download/:filename` | 下载文件 |
| DELETE | `/files/:filename` | 删除文件 |
---
## 目录结构
```text
tmp-upload/
├── main.go # 入口、配置、路由注册 (60 行)
├── embed.go # //go:embed + init() 拼接 (29 行)
├── audit.go # 审计日志子系统 (102 行)
├── quota.go # 配额管理 + formatSize (112 行)
├── handlers.go # HTTP handlers + DTOs (296 行)
├── 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 行)
```
### 单文件部署说明
`embed.go``//go:embed` 把三个静态文件全部编入二进制,
`init()` 中用 `strings.Replace` 把 CSS/JS 拼到 HTML 骨架里生成 `pageHTML`
浏览器访问 `/` 拿到的是**一个**完整 HTML 响应(HTML+CSS+JS 全部内联),
不产生额外的 `<link>` / `<script src=>` 请求。
---
## 测试
```bash
go test ./... # 单元测试(audit 日志格式)
bash security_test.sh # 端到端安全 / 接口测试
go vet ./... # 静态检查
```
---
## 安全相关
* `DELETE /files/:filename` 不要求鉴权 — 部署时建议放在反代之后或加防火墙
* 文件名采用时间戳 + 随机串避免冲突与枚举
* 没有请求体大小硬限制(超出 `-quota` 时上传会失败)
---
## License
Personal project. Use at your own risk.
+102
View File
@@ -0,0 +1,102 @@
package main
import (
"encoding/json"
"fmt"
"log"
"maps"
"os"
"path/filepath"
"sync"
"time"
"github.com/gin-gonic/gin"
)
// -----------------------------------------------------------------------------
// 审计日志 (JSON Lines, 一行一条事件, 落盘到 *auditDir/YYYY-MM-DD.log, 跨日自动轮转)
// -----------------------------------------------------------------------------
var (
auditMu sync.Mutex
auditFile *os.File
auditCurDay string // 当前打开文件对应的日期 (YYYY-MM-DD)
)
// initAudit 创建目录, 打开今天的日志文件
func initAudit() error {
if *auditDir == "" {
log.Println("[audit] disabled (audit dir is empty)")
return nil
}
if err := os.MkdirAll(*auditDir, 0o755); err != nil {
return fmt.Errorf("create audit dir: %w", err)
}
if err := openAuditFor(time.Now()); err != nil {
return err
}
log.Printf("[audit] writing to %s/%s.log", *auditDir, auditCurDay)
return nil
}
// openAuditFor 为指定时间打开对应日期的日志文件. 调用方需持有 auditMu.
func openAuditFor(t time.Time) error {
day := t.Format("2006-01-02")
if day == auditCurDay && auditFile != nil {
return nil
}
if auditFile != nil {
_ = auditFile.Close()
}
path := filepath.Join(*auditDir, day+".log")
f, err := os.OpenFile(path, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o644)
if err != nil {
return fmt.Errorf("open %s: %w", path, err)
}
auditFile = f
auditCurDay = day
return nil
}
// audit 写一条审计事件. fields 里的键会合并到事件 JSON 中.
// 写入失败仅记录到 stdout, 不会影响主流程.
func audit(c *gin.Context, action string, fields map[string]any) {
if *auditDir == "" {
return
}
entry := map[string]any{
"ts": time.Now().Format(time.RFC3339),
"action": action,
"ip": c.ClientIP(),
"method": c.Request.Method,
"path": c.Request.URL.Path,
"ua": c.Request.UserAgent(),
"status": c.Writer.Status(),
"latency": time.Since(c.GetTime("t0")).String(),
}
maps.Copy(entry, fields)
b, err := json.Marshal(entry)
if err != nil {
log.Printf("[audit] marshal err: %v", err)
return
}
b = append(b, '\n')
auditMu.Lock()
defer auditMu.Unlock()
if err := openAuditFor(time.Now()); err != nil {
log.Printf("[audit] open err: %v", err)
return
}
if _, err := auditFile.Write(b); err != nil {
log.Printf("[audit] write err: %v", err)
}
}
// auditT0 记录请求进入时间, 供 audit() 计算 latency
func auditT0() gin.HandlerFunc {
return func(c *gin.Context) {
c.Set("t0", time.Now())
c.Next()
}
}
+57
View File
@@ -0,0 +1,57 @@
package main
import (
"log"
"os"
"path/filepath"
"sync"
"time"
"github.com/robfig/cron/v3"
)
// -----------------------------------------------------------------------------
// TTL 清理器
// -----------------------------------------------------------------------------
var cleanerOnce sync.Once
func startCleaner() {
cleanerOnce.Do(func() {
if err := os.MkdirAll(*uploadDir, 0o755); err != nil {
log.Fatalf("create upload dir failed: %v", err)
}
c := cron.New()
_, err := c.AddFunc("@every "+scanEvery.String(), func() {
now := time.Now()
removed := 0
var removedBytes int64
_ = filepath.Walk(*uploadDir, func(path string, info os.FileInfo, err error) error {
if err != nil || info.IsDir() {
return nil
}
if now.Sub(info.ModTime()) > *fileTTL {
if rmErr := os.Remove(path); rmErr != nil {
log.Printf("[cleaner] remove failed: %s err=%v", path, rmErr)
} else {
log.Printf("[cleaner] removed: %s (age=%v, size=%s)", path, now.Sub(info.ModTime()), formatSize(info.Size()))
removed++
removedBytes += info.Size()
}
}
return nil
})
quotaSub(removedBytes)
// 漂移修正: 每小时一次 rescan 校正任何来源不明的字节数偏差
rescanQuota()
log.Printf("[cleaner] scan done, removed=%d (%s), quota used now=%s",
removed, formatSize(removedBytes), formatSize(quotaUsedSnapshot()))
})
if err != nil {
log.Fatalf("add cron job failed: %v", err)
}
c.Start()
log.Printf("[cleaner] started, schedule=@every %s dir=%s ttl=%s",
scanEvery, *uploadDir, *fileTTL)
})
}
+29
View File
@@ -0,0 +1,29 @@
package main
import (
"strings"
_ "embed"
)
// 嵌入式静态页面 (单文件部署, 把 HTML/CSS/JS 编译进二进制, 无需运行时外部文件)
//go:embed static/index.html.tpl
var indexTpl []byte
//go:embed static/app.css
var appCSS []byte
//go:embed static/app.js
var appJS []byte
// pageHTML is the assembled single-file deployment response.
// Computed once at startup; same bytes served on every GET /.
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)
pageHTML = []byte(s)
}
+296
View File
@@ -0,0 +1,296 @@
package main
import (
"fmt"
"log"
"net/http"
"os"
"path/filepath"
"strings"
"time"
"github.com/gin-gonic/gin"
)
// -----------------------------------------------------------------------------
// 路由处理器
// -----------------------------------------------------------------------------
type fileResponse struct {
Filename string `json:"filename"`
URL string `json:"url"`
Size int64 `json:"size"`
UploadedAt time.Time `json:"uploaded_at"`
ExpiresAt time.Time `json:"expires_at"`
}
func uploadHandler(c *gin.Context) {
f, err := c.FormFile(fieldName)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "missing form field 'file'"})
audit(c, "upload", gin.H{"file": "", "result": "missing_form_field"})
return
}
// 早 reject: 防止 NUL 字节 + 超长文件名打爆 Stat/Save
if strings.ContainsRune(f.Filename, 0) {
c.JSON(http.StatusBadRequest, gin.H{"error": "filename contains null byte"})
audit(c, "upload", gin.H{"file": f.Filename, "result": "null_byte"})
return
}
// Linux/macOS 路径分量 NAME_MAX = 255 字节
if len(f.Filename) > 200 {
c.JSON(http.StatusBadRequest, gin.H{"error": "filename too long (max 200 bytes)"})
audit(c, "upload", gin.H{"file": f.Filename, "result": "filename_too_long"})
return
}
if err := os.MkdirAll(*uploadDir, 0o755); err != nil {
log.Printf("[upload] mkdir failed: %v", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "internal error"})
audit(c, "upload", gin.H{"file": f.Filename, "result": "mkdir_failed"})
return
}
// 配额检查 (单文件能塞下 + 不会超总配额)
if *quota > 0 && f.Size > quotaRemaining() {
used, cap_ := quotaSnapshot()
c.JSON(http.StatusInsufficientStorage, gin.H{
"error": fmt.Sprintf("quota exceeded: %s used / %s cap, file size %s",
formatSize(used), formatSize(cap_), formatSize(f.Size)),
})
audit(c, "upload", gin.H{
"file": f.Filename,
"size": f.Size,
"result": "quota_exceeded",
})
return
}
name := uniqueFilename(*uploadDir, f.Filename)
dst := filepath.Join(*uploadDir, name)
if err := c.SaveUploadedFile(f, dst); err != nil {
log.Printf("[upload] save failed: %v", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "internal error"})
audit(c, "upload", gin.H{"file": f.Filename, "result": "save_failed"})
return
}
// 实际写入的字节数可能与 f.Size 略有差异 (SaveUploadedFile 内部处理), 用 stat 拿真实值
var written int64 = f.Size
if info, statErr := os.Stat(dst); statErr == nil {
written = info.Size()
}
// 原子预留配额, 兜住并发下 pre-save 检查放行的多个请求
if !quotaReserve(written) {
_ = os.Remove(dst)
used, cap_ := quotaSnapshot()
c.JSON(http.StatusInsufficientStorage, gin.H{
"error": fmt.Sprintf("quota exceeded: %s used / %s cap, file size %s",
formatSize(used), formatSize(cap_), formatSize(written)),
})
audit(c, "upload", gin.H{
"file": name,
"size": written,
"result": "quota_exceeded",
})
return
}
now := time.Now()
_ = os.Chtimes(dst, now, now)
c.JSON(http.StatusOK, fileResponse{
Filename: name,
URL: "/download/" + name,
Size: f.Size,
UploadedAt: now,
ExpiresAt: now.Add(*fileTTL),
})
audit(c, "upload", gin.H{
"file": name, // 落盘后的名字 (可能加了 (1) 后缀)
"orig": f.Filename,
"size": f.Size,
"result": "ok",
})
}
// uniqueFilename 把 original 清洗后, 在 dir 中找一个不存在的名字.
// 规则: 原名 → 原名 (1) → 原名 (2) → ...
// 例: report.pdf -> report.pdf
//
// report.pdf (1) -> report.pdf (1)
// .gitignore -> .gitignore
// .gitignore (1) -> .gitignore (1)
func uniqueFilename(dir, original string) string {
// 1. 剥离路径组件, 防穿越
base := filepath.Base(original)
if base == "" || base == "." || base == ".." {
base = "file"
}
// 2. 拆分 stem 和 ext, 处理 .gitignore 这类隐藏文件
ext := filepath.Ext(base)
stem := strings.TrimSuffix(base, ext)
if stem == "" {
// 整个名字都是扩展名 (如 .gitignore), 把整个当 stem
ext = ""
stem = base
}
// 3. 依次尝试 base, base (1), base (2), ...
// 用 O_CREATE|O_EXCL 原子占位, 解决 TOCTOU 竞态 (20 路并发同名上传必须各自拿到不同名字)
// 占位的 0 字节 placeholder 会在 SaveUploadedFile 时被覆盖
for i := range 10000 {
var candidate string
if i == 0 {
candidate = base
} else {
candidate = fmt.Sprintf("%s (%d)%s", stem, i, ext)
}
p := filepath.Join(dir, candidate)
f, err := os.OpenFile(p, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o644)
if err == nil {
f.Close()
return candidate
}
if !os.IsExist(err) {
// 非 "已存在" 错误 (权限/磁盘满等), 兜底用时间戳
log.Printf("[uniqueFilename] open err=%v, fallback to ts", err)
return fmt.Sprintf("%s (%d)%s", stem, time.Now().UnixNano(), ext)
}
}
return fmt.Sprintf("%s (%d)%s", stem, time.Now().UnixNano(), ext)
}
func downloadHandler(c *gin.Context) {
raw := c.Param("filename")
name := filepath.Base(raw)
if name == "" || name == "." || name == ".." ||
strings.ContainsAny(name, "/\\\x00") {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid filename"})
audit(c, "download", gin.H{"file": raw, "result": "invalid_filename"})
return
}
p := filepath.Join(*uploadDir, name)
info, err := os.Stat(p)
if os.IsNotExist(err) {
c.JSON(http.StatusNotFound, gin.H{"error": "file not found or expired"})
audit(c, "download", gin.H{"file": name, "result": "not_found"})
return
}
if err != nil {
log.Printf("[download] stat failed: %v", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "internal error"})
audit(c, "download", gin.H{"file": name, "result": "stat_failed"})
return
}
if info.IsDir() {
c.JSON(http.StatusBadRequest, gin.H{"error": "not a file"})
audit(c, "download", gin.H{"file": name, "result": "is_dir"})
return
}
// 强制下载 + 防 XSS (浏览器不会按扩展名/Content-Type 渲染)
c.Header("Content-Disposition", `attachment; filename="`+name+`"`)
c.Header("X-Content-Type-Options", "nosniff")
// 下载即续期
now := time.Now()
_ = os.Chtimes(p, now, now)
c.File(p)
audit(c, "download", gin.H{
"file": name,
"size": info.Size(),
"result": "ok",
})
}
type fileInfo struct {
Filename string `json:"filename"`
URL string `json:"url"`
Size int64 `json:"size"`
ModTime time.Time `json:"mod_time"`
ExpiresAt time.Time `json:"expires_at"`
}
func listHandler(c *gin.Context) {
entries, err := os.ReadDir(*uploadDir)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
files := make([]fileInfo, 0, len(entries))
for _, e := range entries {
if e.IsDir() {
continue
}
info, err := e.Info()
if err != nil {
continue
}
files = append(files, fileInfo{
Filename: e.Name(),
URL: "/download/" + e.Name(),
Size: info.Size(),
ModTime: info.ModTime(),
ExpiresAt: info.ModTime().Add(*fileTTL),
})
}
c.JSON(http.StatusOK, gin.H{
"count": len(files),
"now": time.Now(),
"ttl": fileTTL.String(),
"quota": func() gin.H {
used, cap_ := quotaSnapshot()
return gin.H{
"used": used,
"cap": cap_,
"used_str": formatSize(used),
"cap_str": formatSize(cap_),
}
}(),
"files": files,
})
}
func deleteHandler(c *gin.Context) {
raw := c.Param("filename")
name := filepath.Base(raw)
if name == "" || name == "." || name == ".." ||
strings.ContainsAny(name, "/\\\x00") {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid filename"})
audit(c, "delete", gin.H{"file": raw, "result": "invalid_filename"})
return
}
p := filepath.Join(*uploadDir, name)
info, err := os.Stat(p)
if os.IsNotExist(err) {
c.JSON(http.StatusNotFound, gin.H{"error": "file not found or already deleted"})
audit(c, "delete", gin.H{"file": name, "result": "not_found"})
return
}
if err != nil {
log.Printf("[delete] stat failed: %v", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "internal error"})
audit(c, "delete", gin.H{"file": name, "result": "stat_failed"})
return
}
if info.IsDir() {
c.JSON(http.StatusBadRequest, gin.H{"error": "not a file"})
audit(c, "delete", gin.H{"file": name, "result": "is_dir"})
return
}
if err := os.Remove(p); err != nil {
log.Printf("[delete] remove failed: %v", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "internal error"})
audit(c, "delete", gin.H{"file": name, "result": "remove_failed"})
return
}
quotaSub(info.Size())
c.JSON(http.StatusOK, gin.H{"deleted": name})
audit(c, "delete", gin.H{"file": name, "size": info.Size(), "result": "ok"})
}
+1 -535
View File
@@ -1,28 +1,14 @@
package main
import (
_ "embed"
"encoding/json"
"flag"
"fmt"
"log"
"maps"
"net/http"
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/gin-gonic/gin"
"github.com/robfig/cron/v3"
)
// 嵌入式静态页面 (单文件部署, 把 HTML 编译进二进制, 无需运行时外部文件)
//
//go:embed static/index.html
var indexHTML []byte
// -----------------------------------------------------------------------------
// 配置 (可被命令行参数覆盖)
// -----------------------------------------------------------------------------
@@ -36,522 +22,10 @@ var (
quota = flag.Int64("quota", 10<<30, "总目录配额 (字节, 默认 10GB, 0=不限)")
)
// -----------------------------------------------------------------------------
// 路由处理器
// -----------------------------------------------------------------------------
const (
fieldName = "file"
)
type fileResponse struct {
Filename string `json:"filename"`
URL string `json:"url"`
Size int64 `json:"size"`
UploadedAt time.Time `json:"uploaded_at"`
ExpiresAt time.Time `json:"expires_at"`
}
// -----------------------------------------------------------------------------
// 审计日志 (JSON Lines, 一行一条事件, 落盘到 *auditDir/YYYY-MM-DD.log, 跨日自动轮转)
// -----------------------------------------------------------------------------
var (
auditMu sync.Mutex
auditFile *os.File
auditCurDay string // 当前打开文件对应的日期 (YYYY-MM-DD)
)
// initAudit 创建目录, 打开今天的日志文件
func initAudit() error {
if *auditDir == "" {
log.Println("[audit] disabled (audit dir is empty)")
return nil
}
if err := os.MkdirAll(*auditDir, 0o755); err != nil {
return fmt.Errorf("create audit dir: %w", err)
}
if err := openAuditFor(time.Now()); err != nil {
return err
}
log.Printf("[audit] writing to %s/%s.log", *auditDir, auditCurDay)
return nil
}
// openAuditFor 为指定时间打开对应日期的日志文件. 调用方需持有 auditMu.
func openAuditFor(t time.Time) error {
day := t.Format("2006-01-02")
if day == auditCurDay && auditFile != nil {
return nil
}
if auditFile != nil {
_ = auditFile.Close()
}
path := filepath.Join(*auditDir, day+".log")
f, err := os.OpenFile(path, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o644)
if err != nil {
return fmt.Errorf("open %s: %w", path, err)
}
auditFile = f
auditCurDay = day
return nil
}
// audit 写一条审计事件. fields 里的键会合并到事件 JSON 中.
// 写入失败仅记录到 stdout, 不会影响主流程.
func audit(c *gin.Context, action string, fields map[string]any) {
if *auditDir == "" {
return
}
entry := map[string]any{
"ts": time.Now().Format(time.RFC3339),
"action": action,
"ip": c.ClientIP(),
"method": c.Request.Method,
"path": c.Request.URL.Path,
"ua": c.Request.UserAgent(),
"status": c.Writer.Status(),
"latency": time.Since(c.GetTime("t0")).String(),
}
maps.Copy(entry, fields)
b, err := json.Marshal(entry)
if err != nil {
log.Printf("[audit] marshal err: %v", err)
return
}
b = append(b, '\n')
auditMu.Lock()
defer auditMu.Unlock()
if err := openAuditFor(time.Now()); err != nil {
log.Printf("[audit] open err: %v", err)
return
}
if _, err := auditFile.Write(b); err != nil {
log.Printf("[audit] write err: %v", err)
}
}
// -----------------------------------------------------------------------------
// 配额 (总目录字节数限制, 默认 10GB, 0=不限)
// -----------------------------------------------------------------------------
var (
quotaMu sync.Mutex
quotaUsed int64 // 当前目录已用字节数
)
// initQuota 启动时扫描目录, 初始化配额计数
func initQuota() {
if *quota <= 0 {
log.Printf("[quota] disabled")
return
}
rescanQuota()
log.Printf("[quota] %s / %s", formatSize(quotaUsed), formatSize(*quota))
}
// rescanQuota 重新扫描目录并重置计数. 调用频率低 (启动 + 清理器每次跑完), 用来修正漂移.
func rescanQuota() {
quotaMu.Lock()
defer quotaMu.Unlock()
var total int64
_ = filepath.Walk(*uploadDir, func(_ string, info os.FileInfo, err error) error {
if err != nil || info.IsDir() {
return nil
}
total += info.Size()
return nil
})
quotaUsed = total
}
// quotaSnapshot 原子返回 used/cap
func quotaSnapshot() (used, cap_ int64) {
quotaMu.Lock()
defer quotaMu.Unlock()
return quotaUsed, *quota
}
// quotaRemaining 返回剩余可上传字节数. quota<=0 时返回 math.MaxInt64.
func quotaRemaining() int64 {
quotaMu.Lock()
defer quotaMu.Unlock()
if *quota <= 0 {
return 1 << 62
}
return *quota - quotaUsed
}
// quotaReserve 原子地预留 n 字节配额: 超限返回 false, 否则扣减并返回 true.
func quotaReserve(n int64) bool {
quotaMu.Lock()
defer quotaMu.Unlock()
if *quota > 0 && quotaUsed+n > *quota {
return false
}
quotaUsed += n
return true
}
func quotaSub(n int64) {
if n <= 0 {
return
}
quotaMu.Lock()
quotaUsed -= n
if quotaUsed < 0 { // 漂移防护
quotaUsed = 0
}
quotaMu.Unlock()
}
// formatSize 字节 → 人类可读
func formatSize(b int64) string {
const (
KB = 1 << 10
MB = 1 << 20
GB = 1 << 30
TB = 1 << 40
)
switch {
case b >= TB:
return fmt.Sprintf("%.2f TB", float64(b)/TB)
case b >= GB:
return fmt.Sprintf("%.2f GB", float64(b)/GB)
case b >= MB:
return fmt.Sprintf("%.2f MB", float64(b)/MB)
case b >= KB:
return fmt.Sprintf("%.2f KB", float64(b)/KB)
default:
return fmt.Sprintf("%d B", b)
}
}
func uploadHandler(c *gin.Context) {
f, err := c.FormFile(fieldName)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "missing form field 'file'"})
audit(c, "upload", gin.H{"file": "", "result": "missing_form_field"})
return
}
// 早 reject: 防止 NUL 字节 + 超长文件名打爆 Stat/Save
if strings.ContainsRune(f.Filename, 0) {
c.JSON(http.StatusBadRequest, gin.H{"error": "filename contains null byte"})
audit(c, "upload", gin.H{"file": f.Filename, "result": "null_byte"})
return
}
// Linux/macOS 路径分量 NAME_MAX = 255 字节
if len(f.Filename) > 200 {
c.JSON(http.StatusBadRequest, gin.H{"error": "filename too long (max 200 bytes)"})
audit(c, "upload", gin.H{"file": f.Filename, "result": "filename_too_long"})
return
}
if err := os.MkdirAll(*uploadDir, 0o755); err != nil {
log.Printf("[upload] mkdir failed: %v", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "internal error"})
audit(c, "upload", gin.H{"file": f.Filename, "result": "mkdir_failed"})
return
}
// 配额检查 (单文件能塞下 + 不会超总配额)
if *quota > 0 && f.Size > quotaRemaining() {
used, cap_ := quotaSnapshot()
c.JSON(http.StatusInsufficientStorage, gin.H{
"error": fmt.Sprintf("quota exceeded: %s used / %s cap, file size %s",
formatSize(used), formatSize(cap_), formatSize(f.Size)),
})
audit(c, "upload", gin.H{
"file": f.Filename,
"size": f.Size,
"result": "quota_exceeded",
})
return
}
name := uniqueFilename(*uploadDir, f.Filename)
dst := filepath.Join(*uploadDir, name)
if err := c.SaveUploadedFile(f, dst); err != nil {
log.Printf("[upload] save failed: %v", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "internal error"})
audit(c, "upload", gin.H{"file": f.Filename, "result": "save_failed"})
return
}
// 实际写入的字节数可能与 f.Size 略有差异 (SaveUploadedFile 内部处理), 用 stat 拿真实值
var written int64 = f.Size
if info, statErr := os.Stat(dst); statErr == nil {
written = info.Size()
}
// 原子预留配额, 兜住并发下 pre-save 检查放行的多个请求
if !quotaReserve(written) {
_ = os.Remove(dst)
used, cap_ := quotaSnapshot()
c.JSON(http.StatusInsufficientStorage, gin.H{
"error": fmt.Sprintf("quota exceeded: %s used / %s cap, file size %s",
formatSize(used), formatSize(cap_), formatSize(written)),
})
audit(c, "upload", gin.H{
"file": name,
"size": written,
"result": "quota_exceeded",
})
return
}
now := time.Now()
_ = os.Chtimes(dst, now, now)
c.JSON(http.StatusOK, fileResponse{
Filename: name,
URL: "/download/" + name,
Size: f.Size,
UploadedAt: now,
ExpiresAt: now.Add(*fileTTL),
})
audit(c, "upload", gin.H{
"file": name, // 落盘后的名字 (可能加了 (1) 后缀)
"orig": f.Filename,
"size": f.Size,
"result": "ok",
})
}
// uniqueFilename 把 original 清洗后, 在 dir 中找一个不存在的名字.
// 规则: 原名 → 原名 (1) → 原名 (2) → ...
// 例: report.pdf -> report.pdf
//
// report.pdf (1) -> report.pdf (1)
// .gitignore -> .gitignore
// .gitignore (1) -> .gitignore (1)
func uniqueFilename(dir, original string) string {
// 1. 剥离路径组件, 防穿越
base := filepath.Base(original)
if base == "" || base == "." || base == ".." {
base = "file"
}
// 2. 拆分 stem 和 ext, 处理 .gitignore 这类隐藏文件
ext := filepath.Ext(base)
stem := strings.TrimSuffix(base, ext)
if stem == "" {
// 整个名字都是扩展名 (如 .gitignore), 把整个当 stem
ext = ""
stem = base
}
// 3. 依次尝试 base, base (1), base (2), ...
// 用 O_CREATE|O_EXCL 原子占位, 解决 TOCTOU 竞态 (20 路并发同名上传必须各自拿到不同名字)
// 占位的 0 字节 placeholder 会在 SaveUploadedFile 时被覆盖
for i := range 10000 {
var candidate string
if i == 0 {
candidate = base
} else {
candidate = fmt.Sprintf("%s (%d)%s", stem, i, ext)
}
p := filepath.Join(dir, candidate)
f, err := os.OpenFile(p, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o644)
if err == nil {
f.Close()
return candidate
}
if !os.IsExist(err) {
// 非 "已存在" 错误 (权限/磁盘满等), 兜底用时间戳
log.Printf("[uniqueFilename] open err=%v, fallback to ts", err)
return fmt.Sprintf("%s (%d)%s", stem, time.Now().UnixNano(), ext)
}
}
return fmt.Sprintf("%s (%d)%s", stem, time.Now().UnixNano(), ext)
}
func downloadHandler(c *gin.Context) {
raw := c.Param("filename")
name := filepath.Base(raw)
if name == "" || name == "." || name == ".." ||
strings.ContainsAny(name, "/\\\x00") {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid filename"})
audit(c, "download", gin.H{"file": raw, "result": "invalid_filename"})
return
}
p := filepath.Join(*uploadDir, name)
info, err := os.Stat(p)
if os.IsNotExist(err) {
c.JSON(http.StatusNotFound, gin.H{"error": "file not found or expired"})
audit(c, "download", gin.H{"file": name, "result": "not_found"})
return
}
if err != nil {
log.Printf("[download] stat failed: %v", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "internal error"})
audit(c, "download", gin.H{"file": name, "result": "stat_failed"})
return
}
if info.IsDir() {
c.JSON(http.StatusBadRequest, gin.H{"error": "not a file"})
audit(c, "download", gin.H{"file": name, "result": "is_dir"})
return
}
// 强制下载 + 防 XSS (浏览器不会按扩展名/Content-Type 渲染)
c.Header("Content-Disposition", `attachment; filename="`+name+`"`)
c.Header("X-Content-Type-Options", "nosniff")
// 下载即续期
now := time.Now()
_ = os.Chtimes(p, now, now)
c.File(p)
audit(c, "download", gin.H{
"file": name,
"size": info.Size(),
"result": "ok",
})
}
type fileInfo struct {
Filename string `json:"filename"`
URL string `json:"url"`
Size int64 `json:"size"`
ModTime time.Time `json:"mod_time"`
ExpiresAt time.Time `json:"expires_at"`
}
func listHandler(c *gin.Context) {
entries, err := os.ReadDir(*uploadDir)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
files := make([]fileInfo, 0, len(entries))
for _, e := range entries {
if e.IsDir() {
continue
}
info, err := e.Info()
if err != nil {
continue
}
files = append(files, fileInfo{
Filename: e.Name(),
URL: "/download/" + e.Name(),
Size: info.Size(),
ModTime: info.ModTime(),
ExpiresAt: info.ModTime().Add(*fileTTL),
})
}
c.JSON(http.StatusOK, gin.H{
"count": len(files),
"now": time.Now(),
"ttl": fileTTL.String(),
"quota": func() gin.H {
used, cap_ := quotaSnapshot()
return gin.H{
"used": used,
"cap": cap_,
"used_str": formatSize(used),
"cap_str": formatSize(cap_),
}
}(),
"files": files,
})
}
func deleteHandler(c *gin.Context) {
raw := c.Param("filename")
name := filepath.Base(raw)
if name == "" || name == "." || name == ".." ||
strings.ContainsAny(name, "/\\\x00") {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid filename"})
audit(c, "delete", gin.H{"file": raw, "result": "invalid_filename"})
return
}
p := filepath.Join(*uploadDir, name)
info, err := os.Stat(p)
if os.IsNotExist(err) {
c.JSON(http.StatusNotFound, gin.H{"error": "file not found or already deleted"})
audit(c, "delete", gin.H{"file": name, "result": "not_found"})
return
}
if err != nil {
log.Printf("[delete] stat failed: %v", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "internal error"})
audit(c, "delete", gin.H{"file": name, "result": "stat_failed"})
return
}
if info.IsDir() {
c.JSON(http.StatusBadRequest, gin.H{"error": "not a file"})
audit(c, "delete", gin.H{"file": name, "result": "is_dir"})
return
}
if err := os.Remove(p); err != nil {
log.Printf("[delete] remove failed: %v", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "internal error"})
audit(c, "delete", gin.H{"file": name, "result": "remove_failed"})
return
}
quotaSub(info.Size())
c.JSON(http.StatusOK, gin.H{"deleted": name})
audit(c, "delete", gin.H{"file": name, "size": info.Size(), "result": "ok"})
}
// -----------------------------------------------------------------------------
// TTL 清理器
// -----------------------------------------------------------------------------
var cleanerOnce sync.Once
func startCleaner() {
cleanerOnce.Do(func() {
if err := os.MkdirAll(*uploadDir, 0o755); err != nil {
log.Fatalf("create upload dir failed: %v", err)
}
c := cron.New()
_, err := c.AddFunc("@every "+scanEvery.String(), func() {
now := time.Now()
removed := 0
var removedBytes int64
_ = filepath.Walk(*uploadDir, func(path string, info os.FileInfo, err error) error {
if err != nil || info.IsDir() {
return nil
}
if now.Sub(info.ModTime()) > *fileTTL {
if rmErr := os.Remove(path); rmErr != nil {
log.Printf("[cleaner] remove failed: %s err=%v", path, rmErr)
} else {
log.Printf("[cleaner] removed: %s (age=%v, size=%s)", path, now.Sub(info.ModTime()), formatSize(info.Size()))
removed++
removedBytes += info.Size()
}
}
return nil
})
quotaSub(removedBytes)
// 漂移修正: 每小时一次 rescan 校正任何来源不明的字节数偏差
rescanQuota()
log.Printf("[cleaner] scan done, removed=%d (%s), quota used now=%s",
removed, formatSize(removedBytes), formatSize(quotaUsedSnapshot()))
})
if err != nil {
log.Fatalf("add cron job failed: %v", err)
}
c.Start()
log.Printf("[cleaner] started, schedule=@every %s dir=%s ttl=%s",
scanEvery, *uploadDir, *fileTTL)
})
}
// quotaUsedSnapshot 不持锁读, 仅用于 cleaner 自身的日志 (允许轻微漂移)
func quotaUsedSnapshot() int64 {
quotaMu.Lock()
defer quotaMu.Unlock()
return quotaUsed
}
// -----------------------------------------------------------------------------
// main
// -----------------------------------------------------------------------------
@@ -570,7 +44,7 @@ func main() {
// 嵌入式首页
r.GET("/", func(c *gin.Context) {
c.Data(http.StatusOK, "text/html; charset=utf-8", indexHTML)
c.Data(http.StatusOK, "text/html; charset=utf-8", pageHTML)
})
// 业务路由
@@ -584,11 +58,3 @@ func main() {
log.Fatal(err)
}
}
// auditT0 记录请求进入时间, 供 audit() 计算 latency
func auditT0() gin.HandlerFunc {
return func(c *gin.Context) {
c.Set("t0", time.Now())
c.Next()
}
}
+112
View File
@@ -0,0 +1,112 @@
package main
import (
"fmt"
"log"
"os"
"path/filepath"
"sync"
)
// -----------------------------------------------------------------------------
// 配额 (总目录字节数限制, 默认 10GB, 0=不限)
// -----------------------------------------------------------------------------
var (
quotaMu sync.Mutex
quotaUsed int64 // 当前目录已用字节数
)
// initQuota 启动时扫描目录, 初始化配额计数
func initQuota() {
if *quota <= 0 {
log.Printf("[quota] disabled")
return
}
rescanQuota()
log.Printf("[quota] %s / %s", formatSize(quotaUsed), formatSize(*quota))
}
// rescanQuota 重新扫描目录并重置计数. 调用频率低 (启动 + 清理器每次跑完), 用来修正漂移.
func rescanQuota() {
quotaMu.Lock()
defer quotaMu.Unlock()
var total int64
_ = filepath.Walk(*uploadDir, func(_ string, info os.FileInfo, err error) error {
if err != nil || info.IsDir() {
return nil
}
total += info.Size()
return nil
})
quotaUsed = total
}
// quotaSnapshot 原子返回 used/cap
func quotaSnapshot() (used, cap_ int64) {
quotaMu.Lock()
defer quotaMu.Unlock()
return quotaUsed, *quota
}
// quotaRemaining 返回剩余可上传字节数. quota<=0 时返回 math.MaxInt64.
func quotaRemaining() int64 {
quotaMu.Lock()
defer quotaMu.Unlock()
if *quota <= 0 {
return 1 << 62
}
return *quota - quotaUsed
}
// quotaReserve 原子地预留 n 字节配额: 超限返回 false, 否则扣减并返回 true.
func quotaReserve(n int64) bool {
quotaMu.Lock()
defer quotaMu.Unlock()
if *quota > 0 && quotaUsed+n > *quota {
return false
}
quotaUsed += n
return true
}
func quotaSub(n int64) {
if n <= 0 {
return
}
quotaMu.Lock()
quotaUsed -= n
if quotaUsed < 0 { // 漂移防护
quotaUsed = 0
}
quotaMu.Unlock()
}
// formatSize 字节 → 人类可读
func formatSize(b int64) string {
const (
KB = 1 << 10
MB = 1 << 20
GB = 1 << 30
TB = 1 << 40
)
switch {
case b >= TB:
return fmt.Sprintf("%.2f TB", float64(b)/TB)
case b >= GB:
return fmt.Sprintf("%.2f GB", float64(b)/GB)
case b >= MB:
return fmt.Sprintf("%.2f MB", float64(b)/MB)
case b >= KB:
return fmt.Sprintf("%.2f KB", float64(b)/KB)
default:
return fmt.Sprintf("%d B", b)
}
}
// quotaUsedSnapshot 不持锁读, 仅用于 cleaner 自身的日志 (允许轻微漂移)
func quotaUsedSnapshot() int64 {
quotaMu.Lock()
defer quotaMu.Unlock()
return quotaUsed
}
+327
View File
@@ -0,0 +1,327 @@
:root {
--bg: #0f1115;
--panel: #1a1d24;
--panel-2: #232732;
--border: #2c3140;
--text: #e6e8ee;
--text-dim: #8a92a3;
--primary: #5b8cff;
--primary-hover: #4a7af0;
--success: #4ade80;
--danger: #f87171;
--warning: #fbbf24;
}
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif;
background: var(--bg);
color: var(--text);
min-height: 100vh;
padding: 40px 20px;
line-height: 1.5;
}
.container { max-width: 880px; margin: 0 auto; }
header { text-align: center; margin-bottom: 32px; }
h1 {
font-size: 28px;
font-weight: 600;
margin-bottom: 8px;
background: linear-gradient(90deg, #5b8cff, #a78bfa);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}
.subtitle { color: var(--text-dim); font-size: 14px; }
.badge {
display: inline-block;
margin-left: 8px;
padding: 2px 8px;
background: var(--panel-2);
border: 1px solid var(--border);
border-radius: 4px;
font-size: 12px;
color: var(--warning);
-webkit-text-fill-color: var(--warning);
vertical-align: middle;
}
.card {
background: var(--panel);
border: 1px solid var(--border);
border-radius: 12px;
padding: 24px;
margin-bottom: 24px;
}
/* Drop zone */
.dropzone {
border: 2px dashed var(--border);
border-radius: 12px;
padding: 48px 24px;
text-align: center;
cursor: pointer;
transition: all 0.2s;
background: var(--panel-2);
user-select: none;
}
.dropzone:hover, .dropzone.dragover, .dropzone:focus-visible {
border-color: var(--primary);
background: rgba(91, 140, 255, 0.05);
outline: none;
}
.dropzone .icon {
font-size: 48px;
margin-bottom: 12px;
color: var(--text-dim);
}
.dropzone .hint { color: var(--text-dim); font-size: 13px; margin-top: 6px; }
/* Buttons */
.btn {
display: inline-block;
padding: 10px 20px;
background: var(--primary);
color: white;
border: none;
border-radius: 8px;
font-size: 14px;
font-weight: 500;
cursor: pointer;
transition: background 0.2s;
}
.btn:hover { background: var(--primary-hover); }
.btn:disabled { background: var(--text-dim); cursor: not-allowed; }
.btn.ghost { background: var(--panel-2); }
.btn.danger { background: var(--danger); }
.btn-row { display: flex; gap: 12px; margin-top: 16px; flex-wrap: wrap; align-items: center; }
/* Progress */
.progress-list { margin-top: 16px; display: flex; flex-direction: column; gap: 8px; }
.progress-item {
background: var(--panel-2);
border: 1px solid var(--border);
border-radius: 8px;
padding: 12px;
transition: opacity 0.3s;
}
.progress-item.done { border-color: var(--success); }
.progress-item.error { border-color: var(--danger); }
.progress-item-head {
display: flex;
justify-content: space-between;
align-items: center;
font-size: 13px;
color: var(--text-dim);
margin-bottom: 6px;
gap: 8px;
}
.progress-item-head .name {
color: var(--text);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
flex: 1;
min-width: 0;
}
.progress-item-head .size-info { font-variant-numeric: tabular-nums; white-space: nowrap; }
.progress-item-head .status {
width: 20px;
height: 20px;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
font-size: 12px;
flex-shrink: 0;
}
.progress-item.done .status { background: var(--success); color: #0f1115; }
.progress-item.error .status { background: var(--danger); color: #0f1115; }
.progress-bar {
height: 4px;
background: var(--border);
border-radius: 2px;
overflow: hidden;
}
.progress-bar > div {
height: 100%;
background: var(--primary);
width: 0%;
transition: width 0.2s;
}
.progress-item.done .progress-bar > div { background: var(--success); width: 100% !important; }
.progress-item.error .progress-bar > div { background: var(--danger); }
.progress-item-actions {
display: flex;
gap: 6px;
margin-top: 8px;
justify-content: flex-end;
}
.progress-item-actions button {
background: transparent;
border: 1px solid var(--border);
color: var(--text-dim);
border-radius: 4px;
padding: 3px 10px;
font-size: 12px;
cursor: pointer;
}
.progress-item-actions button:hover { color: var(--text); border-color: var(--text-dim); }
/* File list */
.files-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 16px;
gap: 12px;
}
.files-header h2 { font-size: 16px; font-weight: 600; }
.files-header .meta { font-size: 12px; color: var(--text-dim); }
/* Quota */
.quota-wrap { margin-bottom: 16px; }
.quota-row {
display: flex;
justify-content: space-between;
align-items: center;
font-size: 12px;
color: var(--text-dim);
margin-bottom: 4px;
}
.quota-row .quota-text strong { color: var(--text); font-variant-numeric: tabular-nums; }
.quota-row .quota-text.warn strong { color: var(--warning); }
.quota-row .quota-text.danger strong { color: var(--danger); }
.quota-bar {
height: 6px;
background: var(--border);
border-radius: 3px;
overflow: hidden;
}
.quota-bar > div {
height: 100%;
background: var(--success);
width: 0%;
transition: width 0.3s, background 0.3s;
}
.quota-bar.warn > div { background: var(--warning); }
.quota-bar.danger > div { background: var(--danger); }
.file-item {
display: flex;
align-items: center;
gap: 12px;
padding: 12px;
background: var(--panel-2);
border: 1px solid var(--border);
border-radius: 8px;
margin-bottom: 8px;
}
.file-icon {
width: 36px;
height: 36px;
border-radius: 6px;
background: var(--panel);
display: flex;
align-items: center;
justify-content: center;
font-size: 18px;
flex-shrink: 0;
}
.file-info { flex: 1; min-width: 0; }
.file-name {
font-size: 14px;
color: var(--text);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.file-meta {
font-size: 12px;
color: var(--text-dim);
margin-top: 2px;
display: flex;
gap: 10px;
flex-wrap: wrap;
align-items: center;
}
.file-meta .ttl { color: var(--warning); font-variant-numeric: tabular-nums; }
.file-meta .ttl.danger { color: var(--danger); }
.file-actions { display: flex; gap: 6px; }
.icon-btn {
width: 32px;
height: 32px;
border-radius: 6px;
border: 1px solid var(--border);
background: var(--panel);
color: var(--text);
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
transition: all 0.2s;
text-decoration: none;
}
.icon-btn:hover { background: var(--primary); border-color: var(--primary); }
.icon-btn.danger:hover { background: var(--danger); border-color: var(--danger); }
.empty {
text-align: center;
padding: 40px 20px;
color: var(--text-dim);
font-size: 14px;
}
.skeleton {
background: linear-gradient(90deg, var(--panel-2) 0%, var(--border) 50%, var(--panel-2) 100%);
background-size: 200% 100%;
animation: shimmer 1.4s infinite;
border-radius: 6px;
height: 56px;
margin-bottom: 8px;
}
@keyframes shimmer {
0% { background-position: 200% 0; }
100% { background-position: -200% 0; }
}
.toast {
position: fixed;
bottom: 24px;
right: 24px;
background: var(--panel);
border: 1px solid var(--border);
border-radius: 8px;
padding: 12px 16px;
font-size: 14px;
box-shadow: 0 8px 24px rgba(0,0,0,0.3);
opacity: 0;
transform: translateY(8px);
transition: all 0.2s;
pointer-events: none;
z-index: 9999;
max-width: 360px;
}
.toast.show { opacity: 1; transform: translateY(0); }
.toast.success { border-left: 3px solid var(--success); }
.toast.error { border-left: 3px solid var(--danger); }
.toast.info { border-left: 3px solid var(--primary); }
footer {
text-align: center;
color: var(--text-dim);
font-size: 12px;
margin-top: 24px;
}
.total-progress {
flex: 1;
height: 4px;
background: var(--border);
border-radius: 2px;
overflow: hidden;
min-width: 120px;
}
.total-progress > div {
height: 100%;
background: var(--primary);
width: 0%;
transition: width 0.2s;
}
.total-label { font-size: 12px; color: var(--text-dim); white-space: nowrap; }
-388
View File
@@ -1,388 +1,3 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>临时文件上传 · TTL 24h</title>
<style>
:root {
--bg: #0f1115;
--panel: #1a1d24;
--panel-2: #232732;
--border: #2c3140;
--text: #e6e8ee;
--text-dim: #8a92a3;
--primary: #5b8cff;
--primary-hover: #4a7af0;
--success: #4ade80;
--danger: #f87171;
--warning: #fbbf24;
}
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif;
background: var(--bg);
color: var(--text);
min-height: 100vh;
padding: 40px 20px;
line-height: 1.5;
}
.container { max-width: 880px; margin: 0 auto; }
header { text-align: center; margin-bottom: 32px; }
h1 {
font-size: 28px;
font-weight: 600;
margin-bottom: 8px;
background: linear-gradient(90deg, #5b8cff, #a78bfa);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}
.subtitle { color: var(--text-dim); font-size: 14px; }
.badge {
display: inline-block;
margin-left: 8px;
padding: 2px 8px;
background: var(--panel-2);
border: 1px solid var(--border);
border-radius: 4px;
font-size: 12px;
color: var(--warning);
-webkit-text-fill-color: var(--warning);
vertical-align: middle;
}
.card {
background: var(--panel);
border: 1px solid var(--border);
border-radius: 12px;
padding: 24px;
margin-bottom: 24px;
}
/* Drop zone */
.dropzone {
border: 2px dashed var(--border);
border-radius: 12px;
padding: 48px 24px;
text-align: center;
cursor: pointer;
transition: all 0.2s;
background: var(--panel-2);
user-select: none;
}
.dropzone:hover, .dropzone.dragover, .dropzone:focus-visible {
border-color: var(--primary);
background: rgba(91, 140, 255, 0.05);
outline: none;
}
.dropzone .icon {
font-size: 48px;
margin-bottom: 12px;
color: var(--text-dim);
}
.dropzone .hint { color: var(--text-dim); font-size: 13px; margin-top: 6px; }
/* Buttons */
.btn {
display: inline-block;
padding: 10px 20px;
background: var(--primary);
color: white;
border: none;
border-radius: 8px;
font-size: 14px;
font-weight: 500;
cursor: pointer;
transition: background 0.2s;
}
.btn:hover { background: var(--primary-hover); }
.btn:disabled { background: var(--text-dim); cursor: not-allowed; }
.btn.ghost { background: var(--panel-2); }
.btn.danger { background: var(--danger); }
.btn-row { display: flex; gap: 12px; margin-top: 16px; flex-wrap: wrap; align-items: center; }
/* Progress */
.progress-list { margin-top: 16px; display: flex; flex-direction: column; gap: 8px; }
.progress-item {
background: var(--panel-2);
border: 1px solid var(--border);
border-radius: 8px;
padding: 12px;
transition: opacity 0.3s;
}
.progress-item.done { border-color: var(--success); }
.progress-item.error { border-color: var(--danger); }
.progress-item-head {
display: flex;
justify-content: space-between;
align-items: center;
font-size: 13px;
color: var(--text-dim);
margin-bottom: 6px;
gap: 8px;
}
.progress-item-head .name {
color: var(--text);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
flex: 1;
min-width: 0;
}
.progress-item-head .size-info { font-variant-numeric: tabular-nums; white-space: nowrap; }
.progress-item-head .status {
width: 20px;
height: 20px;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
font-size: 12px;
flex-shrink: 0;
}
.progress-item.done .status { background: var(--success); color: #0f1115; }
.progress-item.error .status { background: var(--danger); color: #0f1115; }
.progress-bar {
height: 4px;
background: var(--border);
border-radius: 2px;
overflow: hidden;
}
.progress-bar > div {
height: 100%;
background: var(--primary);
width: 0%;
transition: width 0.2s;
}
.progress-item.done .progress-bar > div { background: var(--success); width: 100% !important; }
.progress-item.error .progress-bar > div { background: var(--danger); }
.progress-item-actions {
display: flex;
gap: 6px;
margin-top: 8px;
justify-content: flex-end;
}
.progress-item-actions button {
background: transparent;
border: 1px solid var(--border);
color: var(--text-dim);
border-radius: 4px;
padding: 3px 10px;
font-size: 12px;
cursor: pointer;
}
.progress-item-actions button:hover { color: var(--text); border-color: var(--text-dim); }
/* File list */
.files-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 16px;
gap: 12px;
}
.files-header h2 { font-size: 16px; font-weight: 600; }
.files-header .meta { font-size: 12px; color: var(--text-dim); }
/* Quota */
.quota-wrap { margin-bottom: 16px; }
.quota-row {
display: flex;
justify-content: space-between;
align-items: center;
font-size: 12px;
color: var(--text-dim);
margin-bottom: 4px;
}
.quota-row .quota-text strong { color: var(--text); font-variant-numeric: tabular-nums; }
.quota-row .quota-text.warn strong { color: var(--warning); }
.quota-row .quota-text.danger strong { color: var(--danger); }
.quota-bar {
height: 6px;
background: var(--border);
border-radius: 3px;
overflow: hidden;
}
.quota-bar > div {
height: 100%;
background: var(--success);
width: 0%;
transition: width 0.3s, background 0.3s;
}
.quota-bar.warn > div { background: var(--warning); }
.quota-bar.danger > div { background: var(--danger); }
.file-item {
display: flex;
align-items: center;
gap: 12px;
padding: 12px;
background: var(--panel-2);
border: 1px solid var(--border);
border-radius: 8px;
margin-bottom: 8px;
}
.file-icon {
width: 36px;
height: 36px;
border-radius: 6px;
background: var(--panel);
display: flex;
align-items: center;
justify-content: center;
font-size: 18px;
flex-shrink: 0;
}
.file-info { flex: 1; min-width: 0; }
.file-name {
font-size: 14px;
color: var(--text);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.file-meta {
font-size: 12px;
color: var(--text-dim);
margin-top: 2px;
display: flex;
gap: 10px;
flex-wrap: wrap;
align-items: center;
}
.file-meta .ttl { color: var(--warning); font-variant-numeric: tabular-nums; }
.file-meta .ttl.danger { color: var(--danger); }
.file-actions { display: flex; gap: 6px; }
.icon-btn {
width: 32px;
height: 32px;
border-radius: 6px;
border: 1px solid var(--border);
background: var(--panel);
color: var(--text);
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
transition: all 0.2s;
text-decoration: none;
}
.icon-btn:hover { background: var(--primary); border-color: var(--primary); }
.icon-btn.danger:hover { background: var(--danger); border-color: var(--danger); }
.empty {
text-align: center;
padding: 40px 20px;
color: var(--text-dim);
font-size: 14px;
}
.skeleton {
background: linear-gradient(90deg, var(--panel-2) 0%, var(--border) 50%, var(--panel-2) 100%);
background-size: 200% 100%;
animation: shimmer 1.4s infinite;
border-radius: 6px;
height: 56px;
margin-bottom: 8px;
}
@keyframes shimmer {
0% { background-position: 200% 0; }
100% { background-position: -200% 0; }
}
.toast {
position: fixed;
bottom: 24px;
right: 24px;
background: var(--panel);
border: 1px solid var(--border);
border-radius: 8px;
padding: 12px 16px;
font-size: 14px;
box-shadow: 0 8px 24px rgba(0,0,0,0.3);
opacity: 0;
transform: translateY(8px);
transition: all 0.2s;
pointer-events: none;
z-index: 9999;
max-width: 360px;
}
.toast.show { opacity: 1; transform: translateY(0); }
.toast.success { border-left: 3px solid var(--success); }
.toast.error { border-left: 3px solid var(--danger); }
.toast.info { border-left: 3px solid var(--primary); }
footer {
text-align: center;
color: var(--text-dim);
font-size: 12px;
margin-top: 24px;
}
.total-progress {
flex: 1;
height: 4px;
background: var(--border);
border-radius: 2px;
overflow: hidden;
min-width: 120px;
}
.total-progress > div {
height: 100%;
background: var(--primary);
width: 0%;
transition: width 0.2s;
}
.total-label { font-size: 12px; color: var(--text-dim); white-space: nowrap; }
</style>
</head>
<body>
<div class="container">
<header>
<h1>临时文件传输<span class="badge">TTL 24h</span></h1>
<div class="subtitle">上传后 24 小时内有效 · 被下载会自动续期 · 自动清理</div>
</header>
<div class="card">
<div class="dropzone" id="dropzone" tabindex="0" role="button" aria-label="选择或拖拽文件上传">
<div class="icon"></div>
<div><strong>点击选择文件</strong> </div>
<div class="hint">支持多文件 · 受配额限制</div>
</div>
<input type="file" id="fileInput" multiple hidden />
<div class="progress-list" id="progressList"></div>
<div class="btn-row" id="actionRow" style="display:none">
<div class="total-progress" id="totalProgress" style="display:none"><div></div></div>
<span class="total-label" id="totalLabel" style="display:none"></span>
<button class="btn" id="uploadBtn">开始上传</button>
<button class="btn ghost" id="clearBtn">清空</button>
</div>
</div>
<div class="card">
<div class="files-header">
<h2>文件列表</h2>
<span class="meta" id="filesMeta">加载中...</span>
</div>
<div class="quota-wrap" id="quotaWrap" style="display:none">
<div class="quota-row">
<span class="quota-text" id="quotaText">--</span>
<span id="quotaPercent">--</span>
</div>
<div class="quota-bar" id="quotaBar"><div></div></div>
</div>
<div id="filesList">
<div class="skeleton"></div>
<div class="skeleton"></div>
</div>
</div>
<footer>每个文件 TTL 默认 24 小时, 后台每小时扫描清理 · 每次下载会重置过期时间</footer>
</div>
<div class="toast" id="toast"></div>
<script>
'use strict';
const $ = id => document.getElementById(id);
@@ -869,6 +484,3 @@ function escapeHtml(s) {
// ---------------------------------------------------------------------------
loadFiles();
setInterval(loadFiles, 30000);
</script>
</body>
</html>
+61
View File
@@ -0,0 +1,61 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>临时文件上传 · TTL 24h</title>
<style>
/*EMBED_CSS*/</style>
</head>
<body>
<div class="container">
<header>
<h1>临时文件传输<span class="badge">TTL 24h</span></h1>
<div class="subtitle">上传后 24 小时内有效 · 被下载会自动续期 · 自动清理</div>
</header>
<div class="card">
<div class="dropzone" id="dropzone" tabindex="0" role="button" aria-label="选择或拖拽文件上传">
<div class="icon">⬆</div>
<div><strong>点击选择文件</strong> 或将文件拖拽到此处</div>
<div class="hint">支持多文件 · 受配额限制</div>
</div>
<input type="file" id="fileInput" multiple hidden />
<div class="progress-list" id="progressList"></div>
<div class="btn-row" id="actionRow" style="display:none">
<div class="total-progress" id="totalProgress" style="display:none"><div></div></div>
<span class="total-label" id="totalLabel" style="display:none"></span>
<button class="btn" id="uploadBtn">开始上传</button>
<button class="btn ghost" id="clearBtn">清空</button>
</div>
</div>
<div class="card">
<div class="files-header">
<h2>文件列表</h2>
<span class="meta" id="filesMeta">加载中...</span>
</div>
<div class="quota-wrap" id="quotaWrap" style="display:none">
<div class="quota-row">
<span class="quota-text" id="quotaText">--</span>
<span id="quotaPercent">--</span>
</div>
<div class="quota-bar" id="quotaBar"><div></div></div>
</div>
<div id="filesList">
<div class="skeleton"></div>
<div class="skeleton"></div>
</div>
</div>
<footer>每个文件 TTL 默认 24 小时, 后台每小时扫描清理 · 每次下载会重置过期时间</footer>
</div>
<div class="toast" id="toast"></div>
<script>
/*EMBED_JS*/</script>
</body>
</html>