Beego: If I haven't choose file in multipart form,"GetFile" does not return error

Created on 25 May 2016  ·  4Comments  ·  Source: astaxie/beego

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?

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:

f,h,err:=self.GetFile("avatar")
if err != nil {
    //some code
}
defer f.Close()

All 4 comments

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!

Was this page helpful?
0 / 5 - 0 ratings