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!