1. Upload using the form
-
1. New controller and routing
package controllers import "github.com/astaxie/beego" type UploadFileController struct { beego.Controller } func (self *UploadFileController) Get() { self.TplName = "file.html" } func (self *UploadFileController) Post() { self.TplName = "success.html" }
-
2. Front-end form code
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/file" method="post" enctype="multipart/form-data"> <input type="file" name="file"><br/> <input type="submit" value="提交"> </form> </body> </html>
-
3.
post
Process the uploaded files in the form in the requestfunc (self *UploadFileController) Post() { //1.获取上传的文件(file是表单中的name) f, h, err := self.GetFile("file") // 2.延迟关闭 defer func() { f.Close() }() //3.处理上传的错误 if err != nil { return } //4.获取文件名 filename := h.Filename //5.保存上传的文件(file是表单中的name) self.SaveToFile("file", "static/upload/"+filename) self.TplName = "success.html" }
Second, use ajax
upload files
-
1.
html
Introducejquery
files into the code, and upload using FormData on the front end<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.0.0/jquery.min.js"></script> </head> <body> <input type="file" name="file" id="file"><br/> <input type="button" value="提交" id="btn"> </body> <script> $(function () { $('#btn').on('click', function () { const file = $('#file')[0].files[0]; console.log(file); let formData = new FormData() //第一个file是后端接收的数据,第二个file是要上传的文件,文件内容如下图 formData.append('file', file) $.ajax({ url: '/file', method: 'post', data: formData, contentType: false, processData: false, success: function (response) { console.log(response) } }) }) }) </script> </html>
-
2.
ajax
Introduction to several parameters submittedcontentType=false
Do not use the default contentType of application/x-www-form-urlencodedprocessData
The default istrue
, when set totrue
,jquery ajax
it will not be serialized when submitteddata
, but used directlydata
-
3. Data
ajax
must be returned after using the backendjson
func (self *UploadFileController) Post() { //1.获取上传的文件 f, h, err := self.GetFile("file") // 2.延迟关闭 defer func() { f.Close() }() //3.处理上传的错误 if err != nil { return } //4.获取文件名 filename := h.Filename //5.保存上传的文件 self.SaveToFile("file", "static/upload/"+filename) //self.TplName = "success.html" self.Data["json"] = map[string]string { "code": "200", "message": "上传成功"} self.ServeJSON() }
-
4. Rename the uploaded file according to the upload time (so as not to overwrite the file with the same name)
func (self *UploadFileController) Post() { //1.获取上传的文件 f, h, err := self.GetFile("file") // 2.延迟关闭 defer func() { f.Close() }() //3.处理上传的错误 if err != nil { return } //4.获取文件名 filename := h.Filename // 5.处理上传文件名 time_unix_int := time.Now().Unix() time_unix_str := strconv.FormatInt(time_unix_int, 10) //6.保存上传的文件 self.SaveToFile("file", "static/upload/"+(time_unix_str+"_"+filename)) //self.TplName = "success.html" self.Data["json"] = map[string]string{ "code": "200", "message": "上传成功"} self.ServeJSON() }
3. Upload to Alibaba oss
Cloud server
-
2. The
get
method is the same as before, just render a page -
3.
post
Methodfunc (self *OssFileController) Post() { //1.获取上传的文件 f, h, err := self.GetFile("file") if err != nil { return } //2.先关闭文件流 defer f.Close() //3.获取文件的后缀名 extName := path.Ext(h.Filename) //允许上传的文件后缀名 allowExtMap := map[string]bool{ ".jpg": true, ".png": true, ".gif": true, ".jpeg": true, } if _, ok := allowExtMap[extName]; !ok { return } //4.创建阿里oss实例,参考文档 https://help.aliyun.com/document_detail/32145.html?spm=a2c4g.11186623.6.1060.59a84092knAVrU client, err := oss.New("Endpoint", "yourAccessKeyId", "yourAccessKeySecret") if err != nil { fmt.Println("阿里云上传错误", err) return } //5.指定存储空间 bucket, err := client.Bucket("yourBucketName") if err != nil { fmt.Println("存储空间错误") os.Exit(-1) } day := time.Now().Format("2006/01/02") dir := "static/upload/" + day //6.生成文件名 fileUnixName := strconv.FormatInt(time.Now().Unix(), 10) saveDir := path.Join(dir, fileUnixName+extName) fmt.Println(saveDir, "当前文件路径") //7.上传文件流 err = bucket.PutObject(saveDir, f) if err != nil { return } //8.当前的路径 self.Data["json"] = map[string]string{ "code": "200", "message": "成功", "url": "拼接你的url地址" + saveDir, } self.ServeJSON() }