douyan6958 2014-07-16 18:29
浏览 403

在Go中上传MultipartForm文件时计算SHA1哈希

I'm trying to calculate the sha1 hash of an uploaded file but so far I'm at a dead end. The sample code is as follows:

err := req.ParseMultipartForm(200000)
if err != nil {
    http.Error(w, err.Error(), http.StatusInternalServerError)
    return
}

m := req.MultipartForm
files := m.File["Filedata"]

for i, _ := range files {
        file, err := files[i].Open()
        defer file.Close()
    fh = getFileHash(file)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        break
    }

    dst, err := os.Create(baseDir+fh+".jpg")
    defer dst.Close()
    if err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
            break
    }

    if _, err := io.Copy(dst, file); err != nil {
                http.Error(w, err.Error(), http.StatusInternalServerError)
                break
    }
}

And the content of the getFileHash function is as follows:

func getFileHash (f *os.File) string {
     fstat, err := f.Stat()
     if err != nil {
    panic(err)
     }
     fSize := fstat.Size()
     buf := make([]byte, fSize)
     hash := sha1.New()
     n, err := f.Read(buf)
     if _, err := io.WriteString(hash, string(buf[:n])); err != nil {
           panic(err)
     }
     return string(hash.Sum(nil))
}

I'm getting the following error although I'm not sure how to get around this:

cannot use file (type multipart.File) as type *os.File in function argument: need type assertion

If I test by using a sample hash as the value of "fh", it works just fine.

I know I could simply save the file, calculate the hash, and then move the file although that's extra steps I'd rather not take if possible. I'd appreciate any help you could provide me with.

Thanks!

  • 写回答

2条回答 默认 最新

  • dongta1824 2014-07-16 19:23
    关注

    From http://golang.org/pkg/mime/multipart/#File

    File is an interface to access the file part of a multipart message. Its contents may be either stored in memory or on disk. If stored on disk, the File's underlying concrete type will be an *os.File.

    So you are indeed not passing an *os.File type, since it is in memory. Try accepting multipart.File as a type.

    评论

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集