golang模板上传文件如何验证文件是否为空
golang template upload file how to validate the file is empty
我是 go-lang 的初学者。我在使用 html 模板上传文件时遇到问题。我google很多但是没有解决
<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)
}
不,不读取文件就无法知道文件的长度。 (你可以尝试使用Content-Length header,但你必须知道它可以被修改,因此不可靠)。
获取文件大小的方法如下:
file, handler, err := r.FormFile("receipt") // r is *http.Request
var buff bytes.Buffer
fileSize, err := buff.ReadFrom(file)
fmt.Println(fileSize) // this will return you a file size.
您可以从 header 变量(在您的示例中)读取文件大小,它是一个 FileHeader type, returned by FormValue,包含文件的大小:
file, header, err := req.FormFile("receipt")
if err != nil || header.Size == 0 {
// file was not sent
} else {
// process file
}
虽然我不确定这些数据在安全方面的可靠性如何(我猜攻击者可能会伪造恶意发送到服务器的 headers)。
我是 go-lang 的初学者。我在使用 html 模板上传文件时遇到问题。我google很多但是没有解决
<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)
}
不,不读取文件就无法知道文件的长度。 (你可以尝试使用Content-Length header,但你必须知道它可以被修改,因此不可靠)。
获取文件大小的方法如下:
file, handler, err := r.FormFile("receipt") // r is *http.Request
var buff bytes.Buffer
fileSize, err := buff.ReadFrom(file)
fmt.Println(fileSize) // this will return you a file size.
您可以从 header 变量(在您的示例中)读取文件大小,它是一个 FileHeader type, returned by FormValue,包含文件的大小:
file, header, err := req.FormFile("receipt")
if err != nil || header.Size == 0 {
// file was not sent
} else {
// process file
}
虽然我不确定这些数据在安全方面的可靠性如何(我猜攻击者可能会伪造恶意发送到服务器的 headers)。