Colly 多部分表单上传:轻松实现文件上传

2025-07-11 17:47 更新

需要上传文件到服务器?用 CollyPostMultipart 方法,轻松实现多部分表单上传,无论是图片、文档还是其他文件,都能一键搞定!

一、示例:

package main


import (
    "fmt"
    "io/ioutil"
    "net/http"
    "os"
    "time"


    "github.com/gocolly/colly/v2"
)


// 生成多部分表单数据
func generateFormData() map[string][]byte {
    f, _ := os.Open("example.txt") // 打开本地文件
    defer f.Close()


    imgData, _ := ioutil.ReadAll(f) // 读取文件内容


    return map[string][]byte{
        "firstname": []byte("张三"),
        "lastname":  []byte("李四"),
        "email":     []byte("zhangsan@example.com"),
        "file":      imgData, // 文件内容
    }
}


// 设置本地服务器
func setupServer() {
    var handler http.HandlerFunc = func(w http.ResponseWriter, r *http.Request) {
        fmt.Println("收到请求")
        err := r.ParseMultipartForm(10000000)
        if err != nil {
            fmt.Println("服务器错误:", err)
            w.WriteHeader(500)
            w.Write([]byte("<html><body>Internal Server Error</body></html>"))
            return
        }
        w.WriteHeader(200)
        fmt.Println("上传成功")
        w.Write([]byte("<html><body>Success</body></html>"))
    }


    go http.ListenAndServe(":8080", handler)
}


func main() {
    // 启动本地服务器
    setupServer()


    // 创建收集器
    c := colly.NewCollector(
        colly.AllowURLRevisit(),
        colly.MaxDepth(5),
    )


    // 每次访问页面时,打印内容并上传文件
    c.OnHTML("html", func(e *colly.HTMLElement) {
        fmt.Println("页面内容:", e.Text)
        time.Sleep(1 * time.Second)
        e.Request.PostMultipart("http://localhost:8080/", generateFormData())
    })


    // 在请求前打印日志
    c.OnRequest(func(r *colly.Request) {
        fmt.Println("正在上传文件到:", r.URL.String())
    })


    // 开始上传文件
    c.PostMultipart("http://localhost:8080/", generateFormData())
    c.Wait()
}

运行结果(终端输出):

正在上传文件到: http://localhost:8080/
收到请求
上传成功

二、多部分表单上传的 3 个关键点

关键点 说明 示例代码
生成表单数据 使用 map[string][]byte 存储表单字段和文件内容 generateFormData() 函数
上传文件 使用 PostMultipart 方法上传文件 c.PostMultipart("http://localhost:8080/", generateFormData())
本地测试服务器 用于测试文件上传功能 http.ListenAndServe(":8080", handler)

三、完整实战:上传图片到服务器

假设你想上传一张图片到本地服务器,完整代码如下:

package main


import (
    "fmt"
    "io/ioutil"
    "net/http"
    "os"
    "time"


    "github.com/gocolly/colly/v2"
)


// 生成多部分表单数据
func generateFormData() map[string][]byte {
    f, _ := os.Open("example.jpg") // 打开本地图片
    defer f.Close()


    imgData, _ := ioutil.ReadAll(f) // 读取图片内容


    return map[string][]byte{
        "firstname": []byte("张三"),
        "lastname":  []byte("李四"),
        "email":     []byte("zhangsan@example.com"),
        "file":      imgData, // 图片内容
    }
}


// 设置本地服务器
func setupServer() {
    var handler http.HandlerFunc = func(w http.ResponseWriter, r *http.Request) {
        fmt.Println("收到请求")
        err := r.ParseMultipartForm(10000000)
        if err != nil {
            fmt.Println("服务器错误:", err)
            w.WriteHeader(500)
            w.Write([]byte("<html><body>Internal Server Error</body></html>"))
            return
        }
        w.WriteHeader(200)
        fmt.Println("上传成功")
        w.Write([]byte("<html><body>Success</body></html>"))
    }


    go http.ListenAndServe(":8080", handler)
}


func main() {
    // 启动本地服务器
    setupServer()


    // 创建收集器
    c := colly.NewCollector(
        colly.AllowURLRevisit(),
        colly.MaxDepth(5),
    )


    // 每次访问页面时,打印内容并上传文件
    c.OnHTML("html", func(e *colly.HTMLElement) {
        fmt.Println("页面内容:", e.Text)
        time.Sleep(1 * time.Second)
        e.Request.PostMultipart("http://localhost:8080/", generateFormData())
    })


    // 在请求前打印日志
    c.OnRequest(func(r *colly.Request) {
        fmt.Println("正在上传文件到:", r.URL.String())
    })


    // 开始上传文件
    c.PostMultipart("http://localhost:8080/", generateFormData())
    c.Wait()
}

四、常见问题速查

现象 原因 解决方法
文件上传失败 文件路径错误 检查文件路径是否正确
服务器返回错误 服务器端代码错误 检查服务器端代码是否正确处理多部分表单
上传速度慢 网络问题或文件过大 检查网络连接或减小文件大小

五、1 分钟实验

  1. 打开 Go 环境 → 新建 main.go
  2. 复制上方代码 → 保存本地文件 example.txtexample.jpg → 运行。
  3. 观察终端:文件上传成功,服务器返回“Success”。
以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号