限制FormFile中的文件大小 [英] Limiting file size in FormFile

查看:345
本文介绍了限制FormFile中的文件大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我让用户使用FormFile上传文件。我应该在什么时候检查文件大小是否过大。当我做

$ p $ file,header,fileErr:= r.FormFile $ c>

文件对象已创建。那么我是否已经花费了在整个文件中阅读的成本? 使用 MaxBytesReader 来限制请求的大小。在调用ParseMultiPartForm或FormFile之前,请执行以下行:

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

其中 r * http.Request w http.Response



这限制了整个请求体的大小,而不是单个文件。如果您一次上传单个文件,限制请求主体的大小应该是限制文件大小的良好近似值。



如果您想限制金额的内存而不是请求的主体大小,然后调用 r.ParseMultipartForm(maxMemory),然后调用 r.FormFile()。这将为文件部分使用高达 maxMemory 字节,其余部分存储在磁盘上的临时文件中。


I'm letting users 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 is already created. So have I incurred the cost of reading in the entire file already?

解决方案

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

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

where r is the *http.Request and w is the http.Response.

This limits the size of the entire request body and not an individual file. If you are uploading a single file at a time, limiting the size of the request body should a good approximation of limiting the file size.

If you want to limit the amount of memory used instead of the request body size, then call r.ParseMultipartForm(maxMemory) before calling r.FormFile(). This will use up to maxMemory bytes for file parts, with the remainder stored in temporary files on disk.

这篇关于限制FormFile中的文件大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆