Skip to content

Commit 5d147d8

Browse files
author
cong.li
committed
支持上传到任意目录
1 parent ecf6ea1 commit 5d147d8

File tree

1 file changed

+20
-7
lines changed

1 file changed

+20
-7
lines changed

fs.go

+20-7
Original file line numberDiff line numberDiff line change
@@ -721,7 +721,7 @@ type fileHandler struct {
721721
// To use the operating system's file system implementation,
722722
// use http.Dir:
723723
//
724-
// http.Handle("/", http.FileServer(http.Dir("/tmp")))
724+
// http.Handle("/", http.FileServer(http.Dir("/tmp")))
725725
//
726726
// As a special case, the returned file server redirects any request
727727
// ending in "/index.html" to the same path, without the final
@@ -737,28 +737,40 @@ func (f *fileHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
737737
r.URL.Path = upath
738738
}
739739
if r.Method == "POST" {
740-
uploadFile(w, r, f.root, path.Clean(upath))
740+
if err := uploadFile(w, r, f.root, path.Clean(upath)); err != nil {
741+
log.Printf("upload file failed %s\n", err)
742+
w.WriteHeader(http.StatusInternalServerError)
743+
}
741744
return
742745
}
743746
serveFile(w, r, f.root, path.Clean(upath), true)
744747
log.Printf("%s %s\n", r.Method, filepath.Join(dir, upath))
745748
}
746749

747750
// upload file
748-
func uploadFile(w http.ResponseWriter, r *http.Request, fs FileSystem, name string) {
751+
func uploadFile(w http.ResponseWriter, r *http.Request, fs FileSystem, name string) error {
749752
r.ParseMultipartForm(32 << 20)
750753
file, handler, err := r.FormFile("file")
751754
if err != nil {
752755
log.Printf("read upload form failed %s\n", err)
753-
return
756+
return err
754757
}
755758
var filename = handler.Filename
759+
log.Printf("upload file filename=%s to directory %s", filename, path.Join(dir, name))
760+
if _, err := os.Stat(path.Join(dir, name)); err != nil {
761+
if os.IsNotExist(err) {
762+
log.Printf("%s directory no exist, create it \n", path.Join(dir, name))
763+
if err = os.MkdirAll(path.Join(dir, name), 0731); err != nil {
764+
return err
765+
}
766+
}
767+
}
756768
fh, err := os.Create(path.Join(dir, name, filename))
757769
if err != nil {
758770
log.Printf("upload file filename=%s error, create file failed %s \n", filename, err)
759-
return
771+
return err
760772
}
761-
log.Printf("POST %s\n", fh.Name())
773+
log.Printf("Writing %s\n", fh.Name())
762774
defer file.Close()
763775
var buffer = make([]byte, 10*1024*1024)
764776
for {
@@ -773,7 +785,8 @@ func uploadFile(w http.ResponseWriter, r *http.Request, fs FileSystem, name stri
773785
defer fh.Close()
774786
// write this byte array to our temporary file
775787
// return that we have successfully uploaded our file!
776-
fmt.Fprintf(w, "Successfully Uploaded File\n")
788+
log.Printf("Successfully Uploaded File %s \n", path.Join(dir, name, filename))
789+
return nil
777790
}
778791

779792
// httpRange specifies the byte range to be sent to the client.

0 commit comments

Comments
 (0)