1,占位
uos@uos-PC:~/go/huzh_web$ tree . ├── conf │ └── app.conf ├── controllers │ ├── default.go │ └── fileopt.go ├── go.mod ├── go.sum ├── huzh_web ├── main.go ├── models ├── routers │ └── router.go ├── static │ ├── css │ ├── easyui │ ├── img │ ├── js │ │ └── reload.min.js │ ├── upload │ │ └── 005.png │ └── uploadfile ├── tests │ └── default_test.go └── views ├── fileopt.html ├── fileupload.html ├── index.tpl └── upload.html
2,
fileupload.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>文件上传</title> </head> <body> <form enctype="multipart/form-data" method="post"> <input type="file" name="uploadfilename" /> <input type="submit"> </form> </body> </html>
3, controllor
package controllers import ( "log" "github.com/astaxie/beego" ) type FileUploadController struct { beego.Controller } // 上传文件的页面 func (c * FileUploadController) Get() { c.TplName = "fileupload.html" } // 上传文件 func (this *FileUploadController) Post() { // uploadfilename,这是一个key值,对应的是html中input type-‘file’的name属性值 f, h, err := this.GetFile("uploadfilename") if err != nil { log.Fatal("getfile err", err) } // 关闭上传的文件,不然的话会出现临时文件不能清除的情况 defer f.Close() // 保存位置在 static/upload, 没有文件夹要先创建 this.SaveToFile("uploadfilename", "static/upload/" + h.Filename) // html页面 this.TplName = "fileupload.html" }
3, router
package routers import ( "huzh_web/controllers" "github.com/astaxie/beego" ) func init() { //beego.Router("/", &controllers.MainController{}) //beego.Router("/", &controllers.UploadController{},"*:Get") //beego.Router("/home", &controllers.UploadController{},"*:Post") beego.Router("/fileupload", &controllers.FileUploadController{}) }
4, upload file
uos@uos-PC:~$ curl -X POST -H "Content-Type: multipart/form-data" -F "uploadfilename=@005.png" http://1.1.13.3:8080/fileupload -v Note: Unnecessary use of -X or --request, POST is already inferred. * Expire in 0 ms for 6 (transfer 0x1afef50) * Trying 1.1.13.3... * TCP_NODELAY set * Expire in 200 ms for 4 (transfer 0x1afef50) * Connected to 1.1.13.3 (1.1.13.3) port 8080 (#0) > POST /fileupload HTTP/1.1 > Host: 1.1.13.3:8080 > User-Agent: curl/7.64.0 > Accept: */* > Content-Length: 17228317 > Content-Type: multipart/form-data; boundary=------------------------1bac053d7e95c8a5 > Expect: 100-continue > * Expire in 1000 ms for 0 (transfer 0x1afef50) < HTTP/1.1 100 Continue < HTTP/1.1 200 OK < Content-Length: 285 < Content-Type: text/html; charset=utf-8 < Server: beegoServer:1.12.1 < Date: Tue, 25 Aug 2020 10:06:55 GMT < <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>文件上传</title> </head> <body> <form enctype="multipart/form-data" method="post"> <input type="file" name="uploadfilename" /> <input type="submit"> </form> </body> </html> * Connection #0 to host 1.1.13.3 left intact
原文:https://www.cnblogs.com/eiguleo/p/13561070.html