From 061b0402fcee0763b2eb87e5ad2a31687f95b307 Mon Sep 17 00:00:00 2001 From: Julian Hurst Date: Fri, 13 Jan 2023 12:03:54 +0100 Subject: Add support for downloading files in zip --- main.go | 36 +++++++++++++++++++++++++++++++++++ templates/user.html | 55 ++++++++++++++++++++++++++++++----------------------- 2 files changed, 67 insertions(+), 24 deletions(-) diff --git a/main.go b/main.go index 1eacfa9..b7e8e53 100644 --- a/main.go +++ b/main.go @@ -16,6 +16,7 @@ import ( "encoding/json" "encoding/base64" "sync" + "archive/zip" "github.com/satori/go.uuid" ) @@ -153,10 +154,13 @@ func index(w http.ResponseWriter, r *http.Request) { path.Join(baseDocDir, u.User, file.Name()), }) } + flasherr := consumeFlashError(w, r) data := struct { Docs []Doc + Error string }{ docs, + flasherr, } serveTemplate(w, r, "templates/user.html", data) return @@ -349,6 +353,37 @@ func handleFileServer(dir, prefix string) http.HandlerFunc { } } +func download(w http.ResponseWriter, r *http.Request) { + switch r.Method { + case http.MethodPost: + r.ParseForm() + selection := r.Form["selection"] + if len(selection) == 0 { + sendFlashError(w, r, "/", errors.New("Aucun fichier sélectionné")) + return + } + contentDisposition := fmt.Sprintf("attachment; filename=\"Documents.zip\"") + w.Header().Set("Content-Disposition", contentDisposition) + wr := zip.NewWriter(w) + defer wr.Close() + for _, sel := range selection { + wrc, err := wr.Create(filepath.Base(sel)) + if err != nil { + sendError(w, r, err.Error(), http.StatusInternalServerError) + return + } + f, err := os.Open(sel) + if err != nil { + sendError(w, r, err.Error(), http.StatusInternalServerError) + return + } + io.Copy(wrc, f) + } + default: + sendInvalidMethod(w, r) + } +} + func upload(w http.ResponseWriter, r *http.Request) { switch r.Method { case http.MethodPost: @@ -408,6 +443,7 @@ func main() { http.HandleFunc("/login", login) http.HandleFunc("/logout", logout) http.HandleFunc("/upload", upload) + http.HandleFunc("/download", download) http.HandleFunc("/admin", admin) http.HandleFunc("/admin/users", adminUsers) log.Printf("Serving http://localhost:%d\n", *p) diff --git a/templates/user.html b/templates/user.html index 5e0aa57..f37c2fb 100644 --- a/templates/user.html +++ b/templates/user.html @@ -2,34 +2,41 @@ {{define "content"}}

Espace utilisateur

Documents

+{{if .Error}} +

{{.Error}}

+{{end}}
- - - - - - - - {{range .Docs}} - - - - - - - {{end}} -
Nom du fichierDate de modificationTaille
- - - {{.Name}} - - {{.ModTime}} - - {{.Size}} -
+
+ + + + + + + + {{range .Docs}} + + + + + + + {{end}} +
Nom du fichierDate de modificationTaille
+ + + {{.Name}} + + {{.ModTime}} + + {{.Size}} +
+
+ +
{{end}} -- cgit v1.2.3