我是 go-lang 的初学者。我在使用 html 模板上传文件时遇到问题。我谷歌了很多但没有解决。
<input type="file" name="myfile"/>
使用 func (*Request) FormFile 获取文件。
file, header, err := req.FormFile("receipt")
但是如何从服务器端验证文件是否为空?我知道我可以读取 request.Body 来查找 myfile 是否为空。
有没有更好的实现方法?
最佳答案
我认为在阅读文件之前不可能知道文件的大小。请参阅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.
所以我想您必须将部分内容读入一个小的临时缓冲区并查看大小。
如果您想验证用户是否发送了文件,您可以检查 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)
}
关于file - golang模板上传文件如何验证文件为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33994374/