If I don't choose file in multipart form,"GetFile" does not return error.
Here is my code:
f, h, err := self.GetFile("avatar")
defer f.Close()
If I don't choose file, It will have error:
runtime error: invalid memory address or nil pointer dereference
How to solve this problem?
hi @zhuscat By default will return ErrMissingFile = errors.New("http: no such file") if file not upload.
you need check err before close file , such as like this:
f,h,err:=self.GetFile("avatar")
if err != nil {
//some code
}
defer f.Close()
@ysqi
Thanks! This can solve my problem.
But I'm wondering why the following code(from beego.me) can't work(put defer f.Close to the front):
func (c *FormController) Post() {
f, h, err := c.GetFile("uploadname")
defer f.Close()
if err != nil {
fmt.Println("getfile err ", err)
} else {
c.SaveToFile("uploadname", "/www/"+h.Filename)
}
}
If I don't choose a file, It will have an error:
runtime error: invalid memory address or nil pointer dereference
as you call the f.Close(), while f is nil.
Oh! I get the point!
Most helpful comment
hi @zhuscat By default will return
ErrMissingFile = errors.New("http: no such file")if file not upload.you need check err before close file , such as like this: