Home > Back-end >  How to avoid very large files sent from forms in golang
How to avoid very large files sent from forms in golang

Time:08-20

Hello everyone I ask for your help since I have a question in golang using forms. Suppose I have this field in an html form:

<input type="file" name="file" id="file">

And I want to receive the file in golang, which I do with the following code:

func index(w http.ResponseWriter, r *http.Request) {
    err := r.ParseMultipartForm(0)

    if err != nil {
      log.Print("Error")
    }

    file, _, _ := r.FormFile("file")

    log.Print(file)
}

So far so good, and I think I really have the file. But now my question is, how can I see the weight of the file before having it saved? I mean, if I understand correctly the go documentation says:

The whole request body is parsed and up to a total of maxMemory bytes of its file parts are stored in memory, with the remainder stored on disk in temporary files.

What I understand (please tell me if I'm wrong) is that the file is saved on the server, I mean on the computer, the problem is, if I have a very limited space on my computer, a very large file could not fill my computer space temporarily and crash the server?

How can I avoid this problem? How can I see the size of the file without actually having the file? Or, how can I limit the size of the file that is uploaded to the server without having the file?

I hope I have made myself understood, and I repeat, if I have misunderstood something please tell me. Thanks in advance :D.

CodePudding user response:

You can use MaxBytesReader and avoid accepting larger files.

r.Body = http.MaxBytesReader(w, r.Body, MaxAllowedSize)
err := r.ParseMultipartForm(MaxAllowedSize)
if err != nil {
        fmt.Fprintf(w, "Can not handle files bigger than %dmb, failed with %s", MaxAllowedSize/(1024*1024), err)
        return
}

example handler

CodePudding user response:

You can set it in nginx or apache or whatever you use to reverse proxy.

If you want with std http golang you can set like this.

And last, framework like gin, echo, etc has config to setting max upload files, you can check on their docs.

  •  Tags:  
  • go
  • Related