Add multi-file upload that zips files server-side

This commit is contained in:
root
2026-03-23 17:02:26 +01:00
parent a3348e8795
commit 09d919ca27
4 changed files with 268 additions and 16 deletions

View File

@@ -10,6 +10,7 @@ func RegisterRoutes(r *gin.RouterGroup, h *Handler) {
files := r.Group("/files") files := r.Group("/files")
files.POST("/upload", h.Upload) files.POST("/upload", h.Upload)
files.POST("/upload-multi", h.UploadMulti)
//files.GET("/download/:id", h.Download) //files.GET("/download/:id", h.Download)
files.GET("/view/:id", h.View) files.GET("/view/:id", h.View)

View File

@@ -0,0 +1,57 @@
package file
import (
"net/http"
"strconv"
"time"
"github.com/gin-gonic/gin"
)
// UploadMulti accepts up to 10 files, zips them server-side, and returns a single download/view key.
func (h *Handler) UploadMulti(c *gin.Context) {
if err := c.Request.ParseMultipartForm(0); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
form, err := c.MultipartForm()
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid multipart form"})
return
}
files := form.File["files"]
if len(files) == 0 {
c.JSON(http.StatusBadRequest, gin.H{"error": "missing files"})
return
}
if len(files) > 10 {
c.JSON(http.StatusBadRequest, gin.H{"error": "too many files (max 10)"})
return
}
once := c.PostForm("once") == "true"
durationStr := c.PostForm("duration")
hours, err := strconv.Atoi(durationStr)
if err != nil || hours <= 0 {
hours = 24
}
duration := time.Duration(hours) * time.Hour
record, err := h.service.UploadBundle(files, once, duration)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{
"id": record.ID,
"deletion_id": record.DeletionID,
"filename": record.Filename,
"size": record.Size,
"expires_at": record.ExpiresAt,
"view_key": record.ViewID,
})
}

151
internal/file/zip.go Normal file
View File

@@ -0,0 +1,151 @@
package file
import (
"archive/zip"
"errors"
"fmt"
"io"
"mime/multipart"
"os"
"path/filepath"
"strings"
"time"
"github.com/google/uuid"
)
func safeZipName(name string) string {
name = filepath.Base(name)
name = strings.ReplaceAll(name, "\\", "_")
name = strings.ReplaceAll(name, "/", "_")
name = strings.TrimSpace(name)
if name == "" || name == "." {
return "file"
}
return name
}
func dedupeName(name string, seen map[string]int) string {
if _, ok := seen[name]; !ok {
seen[name] = 1
return name
}
seen[name]++
ext := filepath.Ext(name)
base := strings.TrimSuffix(name, ext)
return fmt.Sprintf("%s (%d)%s", base, seen[name], ext)
}
// UploadBundle zips multiple uploaded files into a single .zip stored on disk and tracked as one FileRecord.
func (s *Service) UploadBundle(files []*multipart.FileHeader, deleteAfterDownload bool, expiresAfter time.Duration) (*FileRecord, error) {
if len(files) == 0 {
return nil, errors.New("no files")
}
if len(files) > 10 {
return nil, errors.New("too many files (max 10)")
}
folderID := uuid.NewString()
folderPath := filepath.Join(s.storageDir, folderID)
if err := os.MkdirAll(folderPath, os.ModePerm); err != nil {
return nil, err
}
zipDiskName := uuid.NewString() + ".zip"
zipPath := filepath.Join(folderPath, zipDiskName)
out, err := os.Create(zipPath)
if err != nil {
return nil, err
}
defer func() {
_ = out.Close()
if err != nil {
_ = os.Remove(zipPath)
}
}()
zw := zip.NewWriter(out)
defer func() { _ = zw.Close() }()
seen := map[string]int{}
for _, fh := range files {
rc, openErr := fh.Open()
if openErr != nil {
err = openErr
return nil, openErr
}
name := dedupeName(safeZipName(fh.Filename), seen)
h, _ := zip.FileInfoHeader(dummyFileInfo{name: name, size: fh.Size, mod: time.Now()})
h.Name = name
h.Method = zip.Deflate
w, createErr := zw.CreateHeader(h)
if createErr != nil {
_ = rc.Close()
err = createErr
return nil, createErr
}
if _, copyErr := io.Copy(w, rc); copyErr != nil {
_ = rc.Close()
err = copyErr
return nil, copyErr
}
_ = rc.Close()
}
if closeErr := zw.Close(); closeErr != nil {
err = closeErr
return nil, closeErr
}
if closeErr := out.Close(); closeErr != nil {
err = closeErr
return nil, closeErr
}
zipDisplayName := fmt.Sprintf("bundle-%d-files.zip", len(files))
f := &FileRecord{
ID: folderID,
DeletionID: uuid.NewString(),
ViewID: uuid.NewString(),
Filename: zipDisplayName,
Path: zipPath,
Size: fileSize(zipPath),
CreatedAt: time.Now(),
ExpiresAt: time.Now().Add(expiresAfter),
DeleteAfterDownload: deleteAfterDownload,
}
if err := s.repo.Create(f); err != nil {
return nil, err
}
return f, nil
}
func fileSize(path string) int64 {
st, err := os.Stat(path)
if err != nil {
return 0
}
return st.Size()
}
// dummyFileInfo provides minimal os.FileInfo for zip headers.
// This avoids relying on the underlying uploaded file having a real modtime.
// (zip.Writer can work without this too, but headers look nicer.)
type dummyFileInfo struct {
name string
size int64
mod time.Time
}
func (d dummyFileInfo) Name() string { return d.name }
func (d dummyFileInfo) Size() int64 { return d.size }
func (d dummyFileInfo) Mode() os.FileMode { return 0o644 }
func (d dummyFileInfo) ModTime() time.Time { return d.mod }
func (d dummyFileInfo) IsDir() bool { return false }
func (d dummyFileInfo) Sys() any { return nil }

View File

@@ -102,7 +102,7 @@
<div id="upload-ui"> <div id="upload-ui">
<div id="drop-zone" class="drop-zone mb-4"> <div id="drop-zone" class="drop-zone mb-4">
<input type="file" id="fileInput" class="hidden"> <input type="file" id="fileInput" class="hidden" multiple>
<div id="dz-content"> <div id="dz-content">
<span id="dz-text" class="text-sm">Click to select or drop file</span> <span id="dz-text" class="text-sm">Click to select or drop file</span>
@@ -232,20 +232,36 @@
input.onchange = () => { input.onchange = () => {
if (input.files.length) { if (input.files.length) {
showFile(input.files[0]); showFiles(input.files);
uploadBtn.disabled = false; uploadBtn.disabled = false;
} else { } else {
uploadBtn.disabled = true; uploadBtn.disabled = true;
} }
}; };
function showFile(file) { function showFiles(fileList) {
const files = Array.from(fileList || []);
if (files.length === 0) return;
const total = files.reduce((acc, f) => acc + f.size, 0);
if (files.length === 1) {
document.getElementById('dz-text').innerText =
`${files[0].name} (${formatBytes(files[0].size)})`;
return;
}
document.getElementById('dz-text').innerText = document.getElementById('dz-text').innerText =
`${file.name} (${formatBytes(file.size)})`; `${files.length} FILES (${formatBytes(total)}) — will be zipped`;
} }
uploadBtn.onclick = () => { uploadBtn.onclick = () => {
if (input.files.length) handleUpload(input.files[0]); if (!input.files.length) return;
if (input.files.length === 1) {
handleUploadSingle(input.files[0]);
} else {
handleUploadMulti(input.files);
}
}; };
cancelBtn.onclick = (e) => { cancelBtn.onclick = (e) => {
@@ -257,7 +273,15 @@
} }
}; };
function handleUpload(file) { function commonFormData() {
const fd = new FormData();
fd.append("once", document.getElementById("once").checked ? "true" : "false");
const hours = parseInt(document.getElementById("duration").value, 10);
fd.append("duration", hours);
return fd;
}
function startUploadUI() {
uploadBtn.disabled = true; uploadBtn.disabled = true;
uploadBtn.innerText = "UPLOADING..."; uploadBtn.innerText = "UPLOADING...";
cancelBtn.classList.remove('hidden'); cancelBtn.classList.remove('hidden');
@@ -265,16 +289,9 @@
progressContainer.classList.remove("hidden"); progressContainer.classList.remove("hidden");
progressText.classList.remove("hidden"); progressText.classList.remove("hidden");
statsText.classList.remove("hidden"); statsText.classList.remove("hidden");
}
const fd = new FormData(); function setupXHRHandlers(xhr) {
fd.append("file", file);
fd.append("once", document.getElementById("once").checked ? "true" : "false");
const hours = parseInt(document.getElementById("duration").value, 10);
fd.append("duration", hours);
const xhr = new XMLHttpRequest();
currentXhr = xhr;
let startTime = Date.now(); let startTime = Date.now();
xhr.upload.onprogress = (e) => { xhr.upload.onprogress = (e) => {
@@ -301,7 +318,6 @@
const data = JSON.parse(xhr.responseText); const data = JSON.parse(xhr.responseText);
if (data.error) throw new Error(data.error); if (data.error) throw new Error(data.error);
// Redirect using view key
window.location.href = "/f/" + data.view_key; window.location.href = "/f/" + data.view_key;
} catch (err) { } catch (err) {
@@ -319,11 +335,38 @@
location.reload(); location.reload();
} }
}; };
}
function handleUploadSingle(file) {
startUploadUI();
const fd = commonFormData();
fd.append("file", file);
const xhr = new XMLHttpRequest();
currentXhr = xhr;
setupXHRHandlers(xhr);
xhr.open("POST", "/api/files/upload"); xhr.open("POST", "/api/files/upload");
xhr.send(fd); xhr.send(fd);
} }
function handleUploadMulti(fileList) {
startUploadUI();
const fd = commonFormData();
Array.from(fileList).forEach(f => fd.append("files", f));
const xhr = new XMLHttpRequest();
currentXhr = xhr;
setupXHRHandlers(xhr);
xhr.open("POST", "/api/files/upload-multi");
xhr.send(fd);
}
function copy(id) { function copy(id) {
const el = document.getElementById(id); const el = document.getElementById(id);
el.select(); el.select();