Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow uploading multiple files at once #11

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 19 additions & 18 deletions server.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ const directoryListingTemplateText = `
</tr>
{{- end }}
{{- if .AllowUpload }}
<tr><td colspan=3><form method="post" enctype="multipart/form-data"><input required name="file" type="file"/><input value="Upload" type="submit"/></form></td></tr>
<tr><td colspan=3><form method="post" enctype="multipart/form-data"><input required name="file" type="file" multiple/><input value="Upload" type="submit"/></form></td></tr>
{{- end }}
</tbody>
</table>
Expand Down Expand Up @@ -200,26 +200,27 @@ func (f *fileHandler) serveDir(w http.ResponseWriter, r *http.Request, osPath st
}

func (f *fileHandler) serveUploadTo(w http.ResponseWriter, r *http.Request, osPath string) error {
if err := r.ParseForm(); err != nil {
return err
}
in, h, err := r.FormFile("file")
if err == http.ErrMissingFile {
w.Header().Set("Location", r.URL.String())
w.WriteHeader(303)
}
if err != nil {
return err
}
outPath := filepath.Join(osPath, filepath.Base(h.Filename))
out, err := os.OpenFile(outPath, os.O_CREATE|os.O_WRONLY, 0600)
mr, err := r.MultipartReader()
if err != nil {
return err
}
defer out.Close()

if _, err := io.Copy(out, in); err != nil {
return err
for {
part, err := mr.NextPart()
if err == io.EOF {
break
} else if err != nil {
return err
} else if part.FormName() == "file" {
outPath := filepath.Join(osPath, filepath.Base(part.FileName()))
out, err := os.OpenFile(outPath, os.O_CREATE|os.O_WRONLY, 0600)
if err != nil {
return err
}
defer out.Close()
if _, err := io.Copy(out, part); err != nil {
return err
}
}
}
w.Header().Set("Location", r.URL.String())
w.WriteHeader(303)
Expand Down