为了账号安全,请及时绑定邮箱和手机立即绑定

为什么上传文件 ~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个赞

客户端正在尝试向服务器发送数据。服务器没有读取数据,它只是查看标题并关闭连接。客户端将此解释为“连接已重置”。这是你无法控制的。

不是检查标题,而是标题可以撒谎,用于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 关注
  • 75 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信