国产chinesehdxxxx野外,国产av无码专区亚洲av琪琪,播放男人添女人下边视频,成人国产精品一区二区免费看,chinese丰满人妻videos

Colly 多部分表單上傳:輕松實(shí)現(xiàn)文件上傳

2025-07-11 17:47 更新

需要上傳文件到服務(wù)器?用 CollyPostMultipart 方法,輕松實(shí)現(xiàn)多部分表單上傳,無論是圖片、文檔還是其他文件,都能一鍵搞定!

一、示例:

package main


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


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


// 生成多部分表單數(shù)據(jù)
func generateFormData() map[string][]byte {
    f, _ := os.Open("example.txt") // 打開本地文件
    defer f.Close()


    imgData, _ := ioutil.ReadAll(f) // 讀取文件內(nèi)容


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


// 設(shè)置本地服務(wù)器
func setupServer() {
    var handler http.HandlerFunc = func(w http.ResponseWriter, r *http.Request) {
        fmt.Println("收到請求")
        err := r.ParseMultipartForm(10000000)
        if err != nil {
            fmt.Println("服務(wù)器錯(cuò)誤:", 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() {
    // 啟動(dòng)本地服務(wù)器
    setupServer()


    // 創(chuàng)建收集器
    c := colly.NewCollector(
        colly.AllowURLRevisit(),
        colly.MaxDepth(5),
    )


    // 每次訪問頁面時(shí),打印內(nèi)容并上傳文件
    c.OnHTML("html", func(e *colly.HTMLElement) {
        fmt.Println("頁面內(nèi)容:", 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()
}

運(yùn)行結(jié)果(終端輸出):

正在上傳文件到: http://localhost:8080/
收到請求
上傳成功

二、多部分表單上傳的 3 個(gè)關(guān)鍵點(diǎn)

關(guān)鍵點(diǎn) 說明 示例代碼
生成表單數(shù)據(jù) 使用 map[string][]byte 存儲表單字段和文件內(nèi)容 generateFormData() 函數(shù)
上傳文件 使用 PostMultipart 方法上傳文件 c.PostMultipart("http://localhost:8080/", generateFormData())
本地測試服務(wù)器 用于測試文件上傳功能 http.ListenAndServe(":8080", handler)

三、完整實(shí)戰(zhàn):上傳圖片到服務(wù)器

假設(shè)你想上傳一張圖片到本地服務(wù)器,完整代碼如下:

package main


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


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


// 生成多部分表單數(shù)據(jù)
func generateFormData() map[string][]byte {
    f, _ := os.Open("example.jpg") // 打開本地圖片
    defer f.Close()


    imgData, _ := ioutil.ReadAll(f) // 讀取圖片內(nèi)容


    return map[string][]byte{
        "firstname": []byte("張三"),
        "lastname":  []byte("李四"),
        "email":     []byte("zhangsan@example.com"),
        "file":      imgData, // 圖片內(nèi)容
    }
}


// 設(shè)置本地服務(wù)器
func setupServer() {
    var handler http.HandlerFunc = func(w http.ResponseWriter, r *http.Request) {
        fmt.Println("收到請求")
        err := r.ParseMultipartForm(10000000)
        if err != nil {
            fmt.Println("服務(wù)器錯(cuò)誤:", 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() {
    // 啟動(dòng)本地服務(wù)器
    setupServer()


    // 創(chuàng)建收集器
    c := colly.NewCollector(
        colly.AllowURLRevisit(),
        colly.MaxDepth(5),
    )


    // 每次訪問頁面時(shí),打印內(nèi)容并上傳文件
    c.OnHTML("html", func(e *colly.HTMLElement) {
        fmt.Println("頁面內(nèi)容:", 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()
}

四、常見問題速查

現(xiàn)象 原因 解決方法
文件上傳失敗 文件路徑錯(cuò)誤 檢查文件路徑是否正確
服務(wù)器返回錯(cuò)誤 服務(wù)器端代碼錯(cuò)誤 檢查服務(wù)器端代碼是否正確處理多部分表單
上傳速度慢 網(wǎng)絡(luò)問題或文件過大 檢查網(wǎng)絡(luò)連接或減小文件大小

五、1 分鐘實(shí)驗(yàn)

  1. 打開 Go 環(huán)境 → 新建 main.go。
  2. 復(fù)制上方代碼 → 保存本地文件 example.txtexample.jpg → 運(yùn)行。
  3. 觀察終端:文件上傳成功,服務(wù)器返回“Success”。
以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號