Study notes: uploading of beego files, including uploading of images

I first extracted some of the contents of the beego upload file from the official documentation, which can better help understand :

In beego you can easily handle file uploads, just don't forget to add this attribute to your form form enctype="multipart/form-data" otherwise your browser won't transfer you Upload file.

After the file is uploaded, it is usually placed in the memory of the system. If the size of the file is larger than the size of the set cache memory, then it is placed in the temporary file. The default cache memory is 64M. You can adjust this cache by Memory size:

beego.MaxMemory = 1<<22

or in the configuration file through the following settings:

maxmemory = 1<<22

Beego provides two very convenient ways to handle file upload:

  1. GetFile(key string) (multipart.File, *multipart.FileHeader, error)

    This method is mainly used for users to read files in the form Name the_file, and then return the corresponding information, the user handles file upload based on these variables: filter, save files, and so on.

  2. SaveToFile(fromfile, tofile string) error

This method is a fast save function based on GetFile. Fromfile is the name of the saved version of the name

<form enctype="multipart/form-data" method="post">
    <input type="file" name="uploadname" />
    <input type="submit">
</form>

in the html form at the time of submission:

func (c *FormController) Post() {
    f, h, err := c.GetFile("uploadname")
    if err != nil {
        log.Fatal("getfile err ", err)
    }
    defer f.Close()
    c.SaveToFile("uploadname", "static/upload/" + h.Filename) // The save location is in static/upload, no folder must be created first.

}

一, file upload

controller file plus test.go file:

package controllers

import (
    "github.com/astaxie/beego"
    "path"
)

type UploadController struct {
    beego.Controller
}

func (this *UploadController) Get() {
    this.TplName="upload.html"     //display start interface}

Func (this *UploadController)Post() {
    file, information, err := this.GetFile("file")  //return file, file information header, error message 
    if err != nil {
        this.Ctx.WriteString("File retrieval failure")
        return
    }
    defer file.Close()    // Close the uploaded file, otherwise the temporary file will not be cleared. mmp is wrong many times _||filename := information. Filename

    filename := information.Filename           //Assign the information of the file header to the filename variableerr =this.SaveToFile("file", path.Join("static/upload",filename))  //Save the path of the file. Save it in static/upload (file name) 
    if err != nil {
        this.Ctx.WriteString("File upload failed!")
    } else {
        this.Ctx.WriteString("File upload succeed!")  //Upload Display information after success}this.TplName = "upload.html"             // Stay in the current interface}

view folder upload.html file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>传文件</title>
</head>
<body>
<form action="/home"  enctype="multipart/form-data"  method="post">
    <input type="file" name ="file"><br><br>    
    <input type="submit" value= "Upload related files">
</form>
</body>
<html>

The above "name = "file"" corresponds to the previous file, information, err := this.GetFile("file")key value Consistent, that is, file,

, and according to the official documentation: SaveToFile(fromfile, tofile string) error, this method is a fast save function based on GetFile

fromfile Is the name in the html form at the time of submission. The router.go file under the

routers folder:

package routers

import (
    "upfile/controllers"
    "github.com/astaxie/beego"
)

func init() {
    beego.Router("/", &controllers.UploadController{},"*:Get")
    beego.Router("/home", &controllers.UploadController{},"*:Post")
}

If you want to upload only the image format, it is also very simple, as long as the test file under the controller folder is slightly Make changes , And that is a plus format restrictions on into it! Not much to say, the above code:

package controllers

import (
    "github.com/astaxie/beego"
    "path"
    "strings"
)

type UploadController struct {
    beego.Controller
}

func (this *UploadController) Get() {

    this.TplName="upload.html"
}

func (this *UploadController)Post() {
    file, information, err := this.GetFile("file")  // return file, file information header, error message 
    if err != nil {
        this.Ctx.WriteString("File retrieval failure")
        return
    } else {
        filename := information.Filename
        picture := strings.Split(filename,".")      // read to string, and separated by .symbol layout := strings.ToLower (picture[len(picture)-1])          // converts alphabetic characters to lowercase, non-alphabetic characters do not process, return this string to a lowercase copy. 

        if layout != "jpg" && layout != "png" && layout != "gif" {
            this.Ctx.WriteString(" Please upload the format Image (png, jpg, gif) ")return      //End the entire program without saving the file}

        Err =this.SaveToFile("file",path.Join("static/upload",filename))
        if err != nil {
            this.Ctx.WriteString("File upload failed!")
        } else {
            this.Ctx.WriteString("File upload succeed!")
        }
    }

    defer file.Close()    //Close the uploaded file, otherwise the snack file will not be cleared.
    this.TplName = "upload.html"
}