File Size Limit in FormFile

I allow users to upload a file using FormFile. At what point should I check if the file size is too large. When i do

 file, header, fileErr := r.FormFile("file")

A file object has already been created. So have I already incurred the cost of reading in the whole file?

+4
source share
4 answers

Use MaxBytesReader to limit the size of the request. Before calling ParseMultiPartForm or FormFile, run the following line:

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

where r- *http.Request, and w- http.Response.

This limits the size of the entire request body, not a single file. If you upload one file at a time, the request body size limit should be a good approximation to the file size limit.

, r.ParseMultipartForm(maxMemory) r.FormFile(). maxMemory , .

+4

FormFile ParseMultiPartForm, , 32M . ParseMultiPartForm , FormFile, , , .

Th Content-Length multipart.FileHeader, , .

, request.Body MaxBytesReader , .

+3

Content-Length, , . , .

MaxBytesReader, :

MaxBytesReader .

:

r.Body = http.MaxBytesReader(w, r.Body, 2 * 1024 * 1024) // 2 Mb
clientFile, handler, err := r.FormFile(formDataKey)
if err != nil {
    log.Println(err)
    return
}

2 , - : multipart: NextPart: http: request body too large

+2

You have a field r.ContentLength int64in the query structure and r.Header.Get("Content-Length") string. Maybe this can help.

+1
source

All Articles