diff --git a/main.go b/main.go index 98b7a57..a6f73f2 100644 --- a/main.go +++ b/main.go @@ -179,9 +179,11 @@ func handleUpload(w http.ResponseWriter, r *http.Request, start time.Time) { return } - targetPath := filepath.Join(uploadDir, id, filename) + targetDir := filepath.Join(uploadDir, id) + targetPath := filepath.Join(targetDir, filename) file, err := os.Create(targetPath) if err != nil { + os.Remove(targetDir) http.Error(w, "Failed to create file", http.StatusInternalServerError) logRequest(r, 500, time.Since(start)) return @@ -193,6 +195,7 @@ func handleUpload(w http.ResponseWriter, r *http.Request, start time.Time) { if err != nil { file.Close() os.Remove(targetPath) + os.Remove(targetDir) if isMaxBytesError(err) { http.Error(w, fmt.Sprintf("File exceeds maximum upload size of %d bytes", maxUploadSize), http.StatusRequestEntityTooLarge) logRequest(r, 413, time.Since(start)) @@ -238,6 +241,7 @@ func handleMultipartUpload(w http.ResponseWriter, r *http.Request, start time.Ti logRequest(r, 400, time.Since(start)) return } + defer r.MultipartForm.RemoveAll() files := r.MultipartForm.File["files"] if len(files) == 0 { @@ -263,11 +267,13 @@ func handleMultipartUpload(w http.ResponseWriter, r *http.Request, start time.Ti } filename := filepath.Base(fileHeader.Filename) - targetPath := filepath.Join(uploadDir, id, filename) + targetDir := filepath.Join(uploadDir, id) + targetPath := filepath.Join(targetDir, filename) dst, err := os.Create(targetPath) if err != nil { src.Close() + os.Remove(targetDir) continue } @@ -277,6 +283,7 @@ func handleMultipartUpload(w http.ResponseWriter, r *http.Request, start time.Ti if err != nil { os.Remove(targetPath) + os.Remove(targetDir) continue } @@ -324,7 +331,7 @@ func handleDownload(w http.ResponseWriter, r *http.Request, start time.Time) { } w.Header().Set("Content-Type", detectContentType(filename)) - w.Header().Set("Content-Disposition", fmt.Sprintf("inline; filename=\"%s\"", filename)) + w.Header().Set("Content-Disposition", mime.FormatMediaType("inline", map[string]string{"filename": filename})) w.Header().Set("Content-Length", fmt.Sprintf("%d", stat.Size())) io.Copy(w, file)