Go - What is multipart.File?

The docs say that

If the file is stored on disk, the file under the concrete type will be * Os.File.

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

My actual problem is that I am trying to get the size of the various files stored in memory that I received using the html form, but I cannot use os.Stat to execute fileInfo.Size () because I do not want to specify the location file, just its 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
}
+5
source share
3 answers

You can use 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)

. , . . , , .

.

+6

parseMultipartForm(0), - , f, _ := FormFile("file"), fi, _ := f.(*os.File).Stat()

+2

Depending on what you want to do with the data, the best thing to do is to read the file into a byte fragment using ioutil.ReadAll. (In the end, you may want data in the form of a byte fragment.) Once you do this, you will find the length with len.

+1
source

All Articles