go如何判断表单文件的大小?

后端接收了前端批量上传的图片,我写的接收文件的代码如下。 我想限制每个图片的大小不超出500kb,但是不知道如何判断这个file的大小。 到godoc一查,发现这是个借口,貌似没提供关于查询文件大小的方法。 请问大佬这时我该如何做?(请看代码倒数第5行)

files := r.MultipartForm.File["file"] //获取上传的文件组
    length := len(files)
    //judge if the arry is empty
    if length == 0 {
        w.Write([]byte("× upload empty file... <br> "))
        return
    }
    if(length>20){
        w.Write([]byte("× upload files number more than 20 ...<br> "))
        return
    }
    //read the array and save the files
    for i := 0; i < length; i++ {
        file, err := files[i].Open()
        //the problem heappend here, how can i judge the size of file ?
        defer file.Close()
        if err != nil {
            log.Fatal(err)
        }
已邀请:

pathbox - https://pathbox.github.io/

赞同来自: BlackCarDriver

for _, fileItem := range files {
    ### fileItem.size 
    file, err := fileItem.Open()
    defer file.Close()
     if err != nil {
         log.Fatal(err)
      }
    ......
}

gosky

赞同来自:

网关配置下限制就好

BlackCarDriver

赞同来自:

问题已解决,谢谢各位!

axlrose

赞同来自:

https://stackoverflow.com/questions/34184568/how-to-get-the-real-file-size-of-a-file-in-a-multipart-form-data-request?rq=1

You cannot expect that the Content-Length header is set for the multipart message (some multipart request types even forbid a content length header). It's only required that either a Content-Length header or a Transfer-Encoding header is present.

There must be no Content-Length header in a part of a multipart message.

However, your sender may set an additional parameter in the disposition header. You could leverage this to set the file size as follows:

Content-Disposition: form-data; name="file"; filename="3byte.txt"; size=123

But this would be purely optional, the parameters's name would be arbitrary, and no sender is required to include this parameter. That means, a HTTP server engine can never rely on it.

要回复问题请先登录注册