Add support for multi-file uploads.

main
diff 2021-03-25 17:43:37 +00:00
parent a62bda0546
commit 408a226956
1 changed files with 41 additions and 18 deletions

55
main.go
View File

@ -27,6 +27,7 @@ import (
"path" "path"
"os" "os"
"mime/multipart"
"io" "io"
"fmt" "fmt"
@ -217,24 +218,25 @@ func setupUpload(server *http.Server, conf Config) {
// Handle upload // Handle upload
r.ParseMultipartForm(20 << 20) // Buffer a maximum of 20MB in memory. r.ParseMultipartForm(20 << 20) // Buffer a maximum of 20MB in memory.
inFile, header, err := r.FormFile("file") files := make([]*multipart.FileHeader, 0, 1)
if err != nil { for _, field := range r.MultipartForm.File {
tpl.ExecuteTemplate(w, "UploadError", err) for _, header := range field {
return // Make sure there's only one file if we only expect one.
if len(files) > 0 && !conf.Multiple {
tpl.ExecuteTemplate(w, "UploadError", "multiple files found, only expected one file. start RUFF with -m for multiple file uploads.")
return
}
files = append(files, header)
}
} }
defer inFile.Close()
outFile, err := os.Create(header.Filename) // Save all files to disk.
if err != nil { for i := range files {
tpl.ExecuteTemplate(w, "UploadError", err) err := saveFile(files[i])
return if err != nil {
} tpl.ExecuteTemplate(w, "UploadError", err)
defer outFile.Close() return
}
_, err = io.Copy(outFile, inFile)
if err != nil {
tpl.ExecuteTemplate(w, "UploadError", err)
return
} }
tpl.ExecuteTemplate(w, "UploadMessage", "Upload successful!") tpl.ExecuteTemplate(w, "UploadMessage", "Upload successful!")
@ -242,6 +244,27 @@ func setupUpload(server *http.Server, conf Config) {
}) })
} }
func saveFile(header *multipart.FileHeader) error {
inFile, err := header.Open()
if err != nil {
return err
}
defer inFile.Close()
outFile, err := os.Create(header.Filename)
if err != nil {
return err
}
defer outFile.Close()
_, err = io.Copy(outFile, inFile)
if err != nil {
return err
}
return nil
}
func shutdown(server *http.Server) { func shutdown(server *http.Server) {
server.Shutdown(context.Background()) server.Shutdown(context.Background())
done <- struct{}{} done <- struct{}{}