Home >Backend Development >Golang >Attachment uploading in Beego - Make your web application richer

Attachment uploading in Beego - Make your web application richer

WBOY
WBOYOriginal
2023-06-23 11:04:431504browse

With the continuous development of web applications, users have higher and higher demands for richer functions and experiences. Among them, attachment uploading is a basic and important function, which not only allows users to upload and share their own files, but also allows developers to easily implement a variety of business scenarios, such as avatar uploading, picture display, file downloading, etc.

Beego is a web framework based on the Go language. It provides a wealth of functions and tools, allowing developers to quickly build efficient, scalable, and secure web applications. In Beego, you can easily implement the attachment upload function in web applications by using its built-in attachment upload tool.

In this article, we will introduce how to use the attachment upload function in Beego, and give some practical considerations and optimization tips.

1. Use Beego's attachment upload function

In Beego, the key to implementing the attachment upload function is to use its built-in file upload tool - beego.Context.Input. This tool provides two methods: RetrieveFile (retrieve uploaded files) and SaveToFile (save uploaded files to disk).

The following is a simple attachment upload sample code:

// 控制器代码
func (c *AttachmentController) Post() {
    _, header, err := c.GetFile("att_file")
    if err != nil {
        // 处理上传失败的情况
        c.Data["json"] = map[string]interface{}{
            "code":    1,
            "message": "Upload failed",
        }
    } else {
        // 处理上传成功的情况
        err = c.SaveToFile("att_file", header.Filename)
        if err != nil {
            c.Data["json"] = map[string]interface{}{
                "code":    1,
                "message": "Save file failed",
            }
        } else {
            c.Data["json"] = map[string]interface{}{
                "code":    0,
                "message": "Upload success",
            }
        }
    }
    c.ServeJSON()
}

// 视图代码
<form method="post" enctype="multipart/form-data" action="/attachment/upload">
  <input type="file" name="att_file" required>
  <input type="submit" value="Upload">
</form>

In the above code, we obtain the uploaded file through the c.GetFile("att_file") method in the controller. If the If the method returns err, it means the upload failed. We can return the corresponding error information in the interface. If the upload is successful, save the file to disk through the c.SaveToFile("att_file", header.Filename) method and return success information.

It should be noted that we specify the enctype attribute of the form as a multipart form data type through the enctype="multipart / form-data" attribute in the view. This is because attachment uploading needs to support multiple types. file, so this attribute is required.

2. Related configurations

In actual development, we need to make some settings for attachment uploading, such as file size limits, file types allowed to be uploaded, directories for uploaded files, etc.

Relevant configurations can be made in the configuration file in beego.AppConfig, for example:

# 支持的文件类型
file_types = ["jpg", "jpeg", "png", "gif", "txt", "doc", "docx", "pdf"]

# 上传文件大小限制
file_size = 10 << 20

# 上传文件目录
attachment_dir = "static/upload"

In the above configuration, we limit the size of user uploaded files to no more than 10M (10<< 20 means converted to bytes), the file types that users are allowed to upload include jpg, jpeg, png, gif, txt, doc, docx, pdf, and the storage directory for uploaded files is specified as static/upload.

It should be noted that the reading of configuration files in Beego is based on reading environment variables, which can be set through the os.Setenv ("environment variable name", "variable value") method. For example:

os.Setenv("file_types", `["jpg", "jpeg", "png", "gif", "txt", "doc", "docx", "pdf"]`)

3. Optimization of attachment upload

In addition to realizing the basic attachment upload function, we also need to pay attention to some additional issues.

  1. Image scaling

In practical applications, we usually need to scale and adapt the uploaded images. Beego provides two tool classes, ImageCropper and ImageFilter, which can easily process images. For example:

import (
    "github.com/astaxie/beego/utils/captcha"
    "github.com/astaxie/beego/utils/captcha/drivers"
)

func (c *AttachmentController) Post() {
    f, h, err := c.GetFile("att_file")
    if err != nil {
        // 处理上传失败的情况
        c.Data["json"] = map[string]interface{}{
            "code":    1,
            "message": "Upload failed",
        }
    } else {
        // 处理上传成功的情况
        fileDir := beego.AppConfig.String("attachment_dir")
        fileName := beego.Date(time.Now(), "20060102150405")+filepath.Ext(h.Filename)
        fPath := fileDir + "/" + fileName
        err = c.SaveToFile("att_file", fPath)
        if err != nil {
            c.Data["json"] = map[string]interface{}{
                "code":    1,
                "message": "Save file failed",
            }
        } else {
            c.Data["json"] = map[string]interface{}{
                "code":    0,
                "message": "Upload success",
                "url":     "/"+fPath,
            }
            fUrl := beego.URLFor("AttachmentController.ShowAttachment", ":filename", fileName)
            c.Data["json"].(map[string]interface{})["url"] = fUrl
        }

        // 图片缩放
        scaleWidth := 800 // 等比例缩放至800
        imageCropper := captcha.NewImageCrop(captcha.DriverImaging, fPath)
        err := imageCropper.Resize(scaleWidth)
        if err != nil {
            beego.Error(err)
        }

        // 图片滤镜
        imageFilter := captcha.NewImageFilter(captcha.DriverImaging, fPath)
        err = imageFilter.Hue(-25).Saturation(10).Brightness(-10).Contrast(-5)
        if err != nil {
            beego.Error(err)
        }
    }
    c.ServeJSON()
}

In the above code, we use the ImageCropper and ImageFilter tool classes to achieve equal scaling and color processing of the image respectively.

  1. Blocked upload

For some larger files, one-time uploading often causes lag and timeout problems. In order to improve the user experience, we can use splitting Block upload method. Beego provides the MultipartReader tool class, which can parse and process form data. For example:

func (c *AttachmentController) ChunkUpload() {
    // 读取表单数据
    reader, _ := c.Ctx.Request.MultipartReader()
    var (
        bigFile *os.File
        noi     int
    )
    for {
        part, err := reader.NextPart()
        if err == io.EOF {
            // 读取完成
            break
        }
        if part.FileName() == "" {
            continue
        }
        fileName := part.FileName()
        bigFile, err = os.OpenFile("static/chunk/"+fileName, os.O_WRONLY|os.O_CREATE, 0666)
        defer bigFile.Close()
        if err != nil {
            c.Data["json"] = map[string]interface{}{
                "code":    1,
                "message": "Create file failed",
            }
            c.ServeJSON()
            return
        }
        buf := make([]byte, 1024*1024) // 1MB的缓存
        for {
            n := 0
            n, err = part.Read(buf)
            noi += n // 总共读取的字节数
            if err != nil {
                if err == io.EOF {
                    break
                } else {
                    c.Data["json"] = map[string]interface{}{
                        "code":    1,
                        "message": "Read file failed",
                    }
                    c.ServeJSON()
                    return
                }
            }
            if _, err = bigFile.Write(buf[:n]); err != nil {
                c.Data["json"] = map[string]interface{}{
                    "code":    1,
                    "message": "Write file failed",
                }
                c.ServeJSON()
                return
            }
        }
    }
    // 返回上传结果
    c.Data["json"] = map[string]interface{}{
        "code":     0,
        "message":  "Upload success",
        "fileSize": noi,
    }
    c.ServeJSON()
}

In the above code, we use the MultipartReader tool class to read the form data in chunks, reading 1MB of data each time and writing it to a temporary file. Finally, we asynchronously merge all the chunked files into a complete file.

4. Summary

In this article, we introduced the attachment upload function in Beego, and explained and optimized some practical problems. By using Beego's attachment upload tool, we can easily implement the attachment upload function of various web applications, thereby improving user experience and development efficiency.

The above is the detailed content of Attachment uploading in Beego - Make your web application richer. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn