dtll2016 2015-11-30 08:35
浏览 219
已采纳

Golang模板上传文件如何验证文件为空

I am a beginner with go-lang. I met a problem when I uploaded a file with html template. I google a lot but not solved.

<input  type="file" name="myfile"/>

Use func (*Request) FormFile get the file.

file, header, err := req.FormFile("receipt")

But how to validate the file whether it is empty from server side? I know I can read request.Body to find whether myfile is empty.

Is there a better way to implement it?

  • 写回答

3条回答 默认 最新

  • duanchen7036 2015-11-30 09:47
    关注

    I don't think it's possible to know the size of the file until you read it. See this answer:

    To read the file content is the only reliable way. Having said that, if the content-lenght is present and is too big, to close the connection would be a reasonable thing to do.

    So I guess you'll have to read a part of the content into a small temporary buffer and look at the size.

    If you want to validate, whether the user even sent a file, you can check against http.ErrMissingFile:

        file, header, err := r.FormFile("f")
        switch err {
        case nil:
            // do nothing
        case http.ErrMissingFile:
            log.Println("no file")
        default:
            log.Println(err)
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 shape_predictor_68_face_landmarks.dat
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料