Go `io.Copy`文件大小与原始文件不同

Go `io.Copy`文件大小与原始文件不同,go,Go,我正在处理多部分/表单数据文件上载,我的后端使用Go io.Copy将表单数据复制到本地文件 func SaveFileHandler() error { ... file := form.File["file_uploaded"] // file uploaded in form src, _ := file.Open() // here the original file size is 35540353 in my case, // which

我正在处理多部分/表单数据文件上载,我的后端使用Go io.Copy将表单数据复制到本地文件

func SaveFileHandler() error {
    ...

    file := form.File["file_uploaded"] // file uploaded in form
    src, _ := file.Open()

    // here the original file size is 35540353 in my case, 
    // which is a video/mp4 file
    fmt.Println(file.Size) 

    // create a local file with same filename
    dst, _ := os.Create(file.Filename)

    // save it
    _, err = io.Copy(dst, src)

    // err is nil
    fmt.Println(err) 

    stat, _ := dst.Stat()
    // then the local file size differs from the original updated one. Why?
    // local file size becomes 35537281 (original one is 35540353)
    fmt.Println(stat.Size()) 
    // meanwhile I can't open the local video/mp4 file, 
    // which seems to be broken due to losing data from `io.Copy`

    ...

怎么可能呢?io.Copy是否有最大缓冲区大小?在这种情况下,文件mime类型重要吗? 我尝试使用png和txt文件,两者都按预期工作


Go版本是go1.12.6 linux/amd64

您的问题中没有太多信息,但是从您所说的,我打赌在您调用dst.Stat之前,数据没有完全刷新到文件中。您可以先关闭文件以确保数据已完全刷新:

func SaveFileHandler() error {
    ...

    // create a local file with same filename
    dst, _ := os.Create(file.Filename)

    // save it
    _, err = io.Copy(dst, src)

    // Close the file
    dst.Close()

    // err is nil
    fmt.Println(err) 

    stat, _ := dst.Stat()    
    ...

有什么错误吗?你要关闭文件吗?谢谢@agillgilla!这就是重点。在刷新文件之前,我调用了stat.Size。谢谢你的回答!当然实际上,我是在io.Copy之前使用mimetype detect包读取源文件的。由于某种原因,包导致原始文件损坏。所以这不应该是io复制问题。非常感谢。