file - golang模板上传文件如何验证文件为空

标签 file templates go upload

我是 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/

相关文章:

android - 如何将 Golang 和 Android 与 socket.io 连接起来?

python - 如何从文件类型获取文件扩展名?

c++ - 使用 C++03 模拟 Variadic 模板时,我们可以在类中使用不同的代码吗?

go - 处理用户回答

arrays - 迭代时更改值

c++ - 如何从模板参数(std::vector 和普通指针)中提取 value_type?

php - 如何手动创建 $_FILES 文件对象?

python - 检查是否存在重复,然后在行中附加一个唯一的数字?

python - 谷歌应用引擎 : How to read text file using python?

C++ 指向成员函数的指针作为模板默认参数