亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么上傳文件 ~2,5 MiB 或更大會導致連接重置?

為什么上傳文件 ~2,5 MiB 或更大會導致連接重置?

Go
汪汪一只貓 2022-10-17 10:12:14
我們正在嘗試通過 POST 請求實現圖像上傳。我們還希望將圖像限制在 ~1,0 MiB。它適用于較小的圖像,但任何 ~2,5 MiB 或更大的東西都會導致連接重置。它似乎也在第一個請求之后向同一個處理程序發送多個請求。main.go:package mainimport (    "log"    "net/http")func main() {    http.HandleFunc("/", uploadHandler)    http.ListenAndServe("localhost:8080", nil)}func uploadHandler(w http.ResponseWriter, r *http.Request) {    if r.Method == "POST" {        postHandler(w, r)        return    } else {        http.ServeFile(w, r, "index.html")    }}func postHandler(w http.ResponseWriter, r *http.Request) {    // Send an error if the request is larger than 1 MiB    if r.ContentLength > 1<<20 {        // if larger than ~2,5 MiB, this will print 2 or more times        log.Println("File too large")        // And this error will never arrive, instead a Connection reset        http.Error(w, "response too large", http.StatusRequestEntityTooLarge)        return    }    return}索引.html:<!DOCTYPE html><html lang="">  <head>    <meta charset="utf-8">    <title></title>  </head>  <body>    <form method="POST" enctype="multipart/form-data">      <input type="file" accept="image/*" name="profile-picture"><br>      <button type="submit" >Upload</button>  </form>  </body></html>上傳 ~2,4 MiB 文件時的輸出$ go run main.go2021/11/23 22:00:14 File too large它還在瀏覽器中顯示“請求太大”上傳 ~2,5 MiB 文件時的輸出$ go run main.go2021/11/23 22:03:25 File too large2021/11/23 22:03:25 File too large瀏覽器現在顯示連接已重置
查看完整描述

1 回答

?
慕娘9325324

TA貢獻1783條經驗 獲得超4個贊

客戶端正在嘗試向服務器發送數據。服務器沒有讀取數據,它只是查看標題并關閉連接??蛻舳藢⒋私忉尀椤斑B接已重置”。這是你無法控制的。

不是檢查標題,而是標題可以撒謊,用于http.MaxBytesReader讀取實際內容,但如果它太大,則會出錯。

const MAX_UPLOAD_SIZE = 1<<20


func postHandler(w http.ResponseWriter, r *http.Request) {

    // Wrap the body in a reader that will error at MAX_UPLOAD_SIZE

    r.Body = http.MaxBytesReader(w, r.Body, MAX_UPLOAD_SIZE)


    // Read the body as normal. Check for an error.

    if err := r.ParseMultipartForm(MAX_UPLOAD_SIZE); err != nil {

        // We're assuming it errored because the body is too large.

        // There are other reasons it could error, you'll have to

        // look at err to figure that out.

        log.Println("File too large")

        http.Error(w, "Your file is too powerful", http.StatusRequestEntityTooLarge)

        return

    }


    fmt.Fprintf(w, "Upload successful")

}

有關更多詳細信息,請參閱如何在 Go 中處理文件上傳。


查看完整回答
反對 回復 2022-10-17
  • 1 回答
  • 0 關注
  • 93 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號