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

59
main.go
View File

@ -27,6 +27,7 @@ import (
"path" "path"
"os" "os"
"mime/multipart"
"io" "io"
"fmt" "fmt"
@ -217,31 +218,53 @@ 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 {
defer inFile.Close() tpl.ExecuteTemplate(w, "UploadError", "multiple files found, only expected one file. start RUFF with -m for multiple file uploads.")
return
outFile, err := os.Create(header.Filename) }
if err != nil { files = append(files, header)
tpl.ExecuteTemplate(w, "UploadError", err) }
return
}
defer outFile.Close()
_, err = io.Copy(outFile, inFile)
if err != nil {
tpl.ExecuteTemplate(w, "UploadError", err)
return
} }
// Save all files to disk.
for i := range files {
err := saveFile(files[i])
if err != nil {
tpl.ExecuteTemplate(w, "UploadError", err)
return
}
}
tpl.ExecuteTemplate(w, "UploadMessage", "Upload successful!") tpl.ExecuteTemplate(w, "UploadMessage", "Upload successful!")
go shutdown(server) go shutdown(server)
}) })
} }
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{}{}