go - `io.Copy` 文件大小与原始文件不同
问题描述
我正在处理多部分/表单数据文件上传,我的后端使用 Goio.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()
...
推荐阅读
- java - JavaFX 按键事件
- c++ - Error in Linked List Insertion at last position
- openedge - 类似的东西:子字符串,但用于整数 - Progress4gl
- javascript - 在最终提交 Django 表单之前在 html 模型中显示警告消息
- spring - Spring Cloud Streams 2.2+ kafka binder embeddedHeaders在APPD添加本机奇点标头后存在本机标头时不会回退
- c++ - for 循环在 switch case 之间拆分的行为
- python - 一句话运行多次,出现不同的错误
- python - RuntimeError:请确保已安装 R(已编辑)
- python - 如何复制选定的文件而不将其移动到python中的另一个目录
- tensorflow - 无法在 TensorFlow 2.x 版的 GraphDef 中加载冻结模型 (.pb)