我們正在嘗試通過POST請求實作圖片上傳。我們還希望將影像限制為 ~1,0 MiB。它適用于較小的影像,但任何 ~2.5 MiB 或更大的影像都會導致連接重置。它似乎也在第一個請求之后向同一個處理程式發送多個請求。
main.go:
package main
import (
"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.go
2021/11/23 22:00:14 File too large
它還在瀏覽器中顯示“請求太大”
上傳 ~2,5 MiB 檔案時的輸出
$ go run main.go
2021/11/23 22:03:25 File too large
2021/11/23 22:03:25 File too large
瀏覽器現在顯示連接已重置
uj5u.com熱心網友回復:
客戶端正在嘗試向服務器發送資料。服務器不讀取資料,它只是查看標題并關閉連接。客戶端將此解釋為“連接已重置”。這是你無法控制的。
不是檢查頭部,而是頭部可以撒謊,用于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 中處理檔案上傳。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/364749.html
下一篇:在Go中關閉客戶端服務器通信
