Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go - What is really a multipart.File?

Tags:

go

In the docs it is said that

If stored on disk, the File's underlying concrete type will be an *os.File.

In this case everything is clear. Great. But, what happens if not, if the file is stored in memory?

My actual problem is that I´m trying to get the size of the different files stored in memory that I got though an html form but I can not use os.Stat to do fileInfo.Size() because I don´t have the location of the file, just it´s name.

fhs := req.MultipartForm.File["files"]
for _, fileHeader := range fhs {
    file, _ := fileHeader.Open()
    log.Println(len(file)) // Gives an error because is of type multipart.File
    fileInfo, err  := os.Stat(fileHeader.Filename) // Gives an error because it´s just the name, not the complete path

    // Here I would do things with the file
}
like image 293
AlvaroSantisteban Avatar asked Mar 08 '13 13:03

AlvaroSantisteban


1 Answers

You can exploit the fact that multipart.File implements io.Seeker to find its size.

cur, err := file.Seek(0, 1)
size, err := file.Seek(0, 2)
_, err := file.Seek(cur, 0)

The first line finds the file's current offset. The second seeks to the end of the file and returns where it is in relation to the beginning of the file. This is the size of the file. The third seeks to the offset we were at before trying to find the size.

You can read more about the seek method here.

like image 153
Stephen Weinberg Avatar answered Oct 17 '22 09:10

Stephen Weinberg