Skip to content

Commit 6b44dd8

Browse files
author
cong.li
committed
简化 curl 命令行上传文件的方式
1 parent e575456 commit 6b44dd8

File tree

2 files changed

+25
-4
lines changed

2 files changed

+25
-4
lines changed

README.md

+8
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,15 @@
1414
httpfs --version
1515
v0.2.13 h1:PMdqIhrKOVJx+/wtPUK67bbKx23aHzpc5m4CgnHo6gU=
1616
```
17+
18+
命令行上传文件
19+
```shell
20+
curl -T filename http://127.0.0.1:8080/direcotry/
21+
```
22+
23+
浏览器上传文件
1724
![demo](demo.gif)
25+
1826
# 特性
1927
* 单文件,免安装,静态编译无依赖
2028
* 支持Linux,Windows,Mac OSX 等

fs.go

+17-4
Original file line numberDiff line numberDiff line change
@@ -736,7 +736,7 @@ func (f *fileHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
736736
upath = "/" + upath
737737
r.URL.Path = upath
738738
}
739-
if r.Method == "POST" {
739+
if r.Method == http.MethodPost || r.Method == http.MethodPut {
740740
if err := uploadFile(w, r, f.root, path.Clean(upath)); err != nil {
741741
log.Printf("upload file failed %s\n", err)
742742
w.WriteHeader(http.StatusInternalServerError)
@@ -750,12 +750,12 @@ func (f *fileHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
750750
// upload file
751751
func uploadFile(w http.ResponseWriter, r *http.Request, fs FileSystem, name string) error {
752752
r.ParseMultipartForm(32 << 20)
753-
file, handler, err := r.FormFile("file")
753+
file, filename, err := getFilefromRequest(r)
754754
if err != nil {
755755
log.Printf("read upload form failed %s\n", err)
756756
return err
757757
}
758-
var filename = handler.Filename
758+
defer file.Close()
759759
log.Printf("upload file filename=%s to directory %s", filename, path.Join(dir, name))
760760
if _, err := os.Stat(path.Join(dir, name)); err != nil {
761761
if os.IsNotExist(err) {
@@ -771,7 +771,6 @@ func uploadFile(w http.ResponseWriter, r *http.Request, fs FileSystem, name stri
771771
return err
772772
}
773773
log.Printf("Writing %s\n", fh.Name())
774-
defer file.Close()
775774
var buffer = make([]byte, 10*1024*1024)
776775
for {
777776
n, err := file.Read(buffer)
@@ -789,6 +788,20 @@ func uploadFile(w http.ResponseWriter, r *http.Request, fs FileSystem, name stri
789788
return nil
790789
}
791790

791+
func getFilefromRequest(r *http.Request) (io.ReadCloser, string, error) {
792+
if r.Method != http.MethodPut && r.Method != http.MethodPost {
793+
return nil, "", errors.New("only GET and HEAD method support")
794+
}
795+
if err := r.ParseMultipartForm(32 << 20); err != nil {
796+
return r.Body, path.Base(r.URL.Path), nil
797+
}
798+
file, handler, err := r.FormFile("file")
799+
if err != nil {
800+
return r.Body, path.Base(r.URL.Path), nil
801+
}
802+
return file, handler.Filename, nil
803+
}
804+
792805
// httpRange specifies the byte range to be sent to the client.
793806
type httpRange struct {
794807
start, length int64

0 commit comments

Comments
 (0)