How to configure file upload size limit in Golang project?

WBOY
Release: 2024-05-31 10:32:49
Original
546 people have browsed it

Configuring the file upload size limit in the Golang project: Set the MaxFileSize field of the FileHeader type attribute in http.Request. Create a file upload handler and set an upload file size limit. Parse multi-part forms and extract uploaded files. Save the file to disk. Returns a success response or an error response if the file size exceeds the limit.

如何在 Golang 项目中配置文件上传大小限制?

How to configure file upload size limit in Golang project

In Golang project, configuring upload size limit involves settingMaxFileSize field, which is a FileHeader type attribute of http.Request. Here's how to do it:

package main

import (
    "fmt"
    "log"
    "net/http"
    "os"
)

func main() {
    // 设置上传文件大小限制为 10 MB
    maxFileSize := int64(10 * 1024 * 1024)

    // 创建文件上传处理程序
    http.HandleFunc("/upload", func(w http.ResponseWriter, r *http.Request) {
        // 检查请求是否是多部分表单
        if r.Method == "POST" && r.MultipartForm == nil {
            http.Error(w, "请求不是多部分表单", http.StatusBadRequest)
            return
        }

        // 解析多部分表单
        if err := r.ParseMultipartForm(maxFileSize); err != nil {
            http.Error(w, fmt.Sprintf("解析表单时出错:%v", err), http.StatusInternalServerError)
            return
        }

        // 提取上传文件
        file, fileHeader, err := r.FormFile("file")
        if err != nil {
            http.Error(w, fmt.Sprintf("提取文件时出错:%v", err), http.StatusBadRequest)
            return
        }
        defer file.Close()

        // 将文件保存到磁盘
        dst, err := os.Create("uploaded_file")
        if err != nil {
            http.Error(w, fmt.Sprintf("保存文件时出错:%v", err), http.StatusInternalServerError)
            return
        }
        defer dst.Close()

        if _, err = io.Copy(dst, file); err != nil {
            http.Error(w, fmt.Sprintf("复制文件时出错:%v", err), http.StatusInternalServerError)
            return
        }

        // 返回成功响应
        fmt.Fprintf(w, "文件上传成功!")
    })

    // 启动服务器
    log.Fatal(http.ListenAndServe(":8080", nil))
}
Copy after login

Practical example:

Use Postman or cURL to upload a file larger than 10 MB, you will receive an error response as follows Display:

{
    "error": "文件大小超出了限制"
}
Copy after login

The above is the detailed content of How to configure file upload size limit in Golang project?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!