go framework bee upload files

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. postProcess the uploaded files in the form in the request

    func (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 ajaxupload files

  • 1. htmlIntroduce jqueryfiles 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>
    

    Insert picture description here

  • 2. ajaxIntroduction to several parameters submitted

    • contentType=falseDo not use the default contentType of application/x-www-form-urlencoded
    • processDataThe default is true, when set to true, jquery ajaxit will not be serialized when submitted data, but used directlydata
  • 3. Data ajaxmust 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 ossCloud server

  • 1. Document address

  • 2. The getmethod is the same as before, just render a page

  • 3. postMethod

    
    func (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()
    }
    

Guess you like

Origin blog.csdn.net/kuangshp128/article/details/108928347