go 上传文件
package main
import (
"fmt"
"log"
"github.com/gin-gonic/gin"
)
/*
执行命令:
curl -X POST http://localhost:8080/upload -F "file=@/path/main.zip" -H "Content-Type:multipart/form-data"
*/
func main() {
r := gin.Default()
// Upload single file
r.MaxMultipartMemory = 8 << 20
r.POST("/upload", func(c *gin.Context) {
file, _ := c.FormFile("file")
log.Println(file.Filename)
dst := "./" + file.Filename
//上传至指定的完整文件路径
c.SaveUploadedFile(file, dst)
c.String(200, fmt.Sprintf("'%s' upload", file.Filename))
})
r.Run(":8080")
}
###启动
go run example.go
###抓包
#抓包
tcpdump -vvv -X -n -i any -s0 port 8080 -w test.pcap
###客户端请求 上传文件
接着在另个会话执行
curl -X POST http://localhost:8080/upload -F "file=@/path/main.zip" -H "Content-Type:multipart/form-data"
# 以下是抓包内容 http/1.1
HTTP/1.1 100 Continue
POST /upload HTTP/1.1
Host: localhost:8080
User-Agent: curl/7.61.1
Accept: */*
Content-Length: 1143
Content-Type: multipart/form-data; boundary=------------------------fc4cffd8a2c2f658
Expect: 100-continue
--------------------------fc4cffd8a2c2f658
Content-Disposition: form-data; name="file"; filename="main.zip"
Content-Type: application/octet-stream
PK........F..X...!....4.......main.goUT ....
f...fux..............T.N.@.}..b.....M/..%..E...D(.J....d....%@Q..3......).......iyy.'...U.....A.GL .O.kY...tS?.J....6'Z...X......F...."ix{a..jr.=0b.U V8..j..IR...l_....8.sx'-....jeux........g.%i..(v:..s_;....$.'....`.,ay.&......?.9q.RR...0.M....;o.G}`..D../....o.....X..-/.o..hB&....nxc...cLIXHD.(..A_SX5...K..1.........*%..{F....Q}@.cx. .......lp..)....nU.]............sm...V....7..jq..HC......."..
....%(./K...OV$....FTB9.k.nV...Z.r`#nX.il...=._.....)~K.._.v.R{..(Z'..J.+.
-..F..@.E.1?D.u..>.l(...[..8..75....W.Tp.. #.D.a*x%....4of..........$^.JH%.`......p2...W.....y^...Sm].....`."6.....wR..BU.({..K...6.]+
.m[.\J..Y.."+../.k(...G....d$4aA..M.Go.Nl.-..;c..].%..)
....
..0..H.`./]7+....,."w.P.#.*.....^..cWa2..-.=.'.(%....u...n\.........\M..^.A.;.(0.|.ti.'.$..k;8L..i.5.U.CafX5l.V.~....N.JX8....?.PK..........F..X...!....4.....................main.goUT.....
fux.............PK..........M...L.....
--------------------------fc4cffd8a2c2f658--
HTTP/1.1 200 OK
Content-Type: text/plain; charset=utf-8
Date: Fri, 05 Apr 2024 12:49:59 GMT
Content-Length: 17
'main.zip' upload
上面的显示,
来一张图片,
对了,如果不用curl 方式可以在浏览器打开 html 请求服务器上传文件
<!DOCTYPE html>
<html>
<body>
<h2>Upload File</h2>
<form action="http://localhost:8080/upload" method="post" enctype="multipart/form-data">
Select file to upload:
<input type="file" name="file" id="file">
<input type="submit" value="Upload File" name="submit">
</form>
</body>
</html>